在ASP.NET MVC中更改默认数据库的解决方法可以通过修改Web.config文件中的连接字符串实现。以下是一个示例代码:
在上面的示例中,将连接字符串中的"Initial Catalog"属性更改为你想要连接的数据库名称。确保数据库已经存在,并具有与连接字符串中指定的名称相匹配的表。
另外,你还可以使用ASP.NET Identity框架提供的IdentityDbContext来更改默认的数据库。以下是一个示例代码:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
: base("YourDatabaseConnectionName", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
在上面的示例中,将构造函数中的"YourDatabaseConnectionName"更改为你在Web.config文件中定义的连接字符串的名称。确保连接字符串的名称与IdentityDbContext的构造函数参数名称相匹配。
然后,在IdentityConfig.cs文件中,使用ApplicationDbContext作为IdentityDbContext的派生类,如下所示:
public class ApplicationUserManager : UserManager
{
public ApplicationUserManager(IUserStore store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore(context.Get()));
// 省略其他代码...
return manager;
}
}
在上面的示例中,使用ApplicationDbContext作为UserStore的类型参数,以便使用自定义的数据库连接。
通过上述方法,你可以在ASP.NET MVC应用程序中更改默认数据库。