Asp.Net Mvc 默认应用程序 dbcontext 类移动到另一个文件夹



我正在建立一个asp MVC网站。我正在为我的网站使用身份验证,因此我从默认模板中采用了默认身份验证方法。我现在完全混淆了身份应用程序数据库上下文类和我的应用程序的自定义数据库上下文类。我对此有很多问题..

1( 我应该为每个数据库上下文单独启用迁移吗?

2( 我可以将两个上下文的数据库指向单个数据库吗?(我看到答案说可以做到..(这有什么问题吗?

3(是否可以将Identitymodel.cs类从 models 文件夹移动到名为"数据库"的自定义文件夹,其中存在另一个数据库上下文?我看到命名空间仍然保留dbcontext.models而不是dbcontext.databases

有人可以回答我吗..我已经查找了与此相关的所有问题,仍然无法消除我的疑虑。

1(否

2(是的,你可以这样做,但最好在一个上下文中实现它。 你怎么能做到这一点?你的答案在这里: 创建类名ApplicationDbcontext

ApplicationDbcontext.cs

public class ApplicationDbContext :IdentityDbContext<User, Role, Guid, UserLogin, UserRole, UserClaim>
{
public ApplicationDbContext() :
base("Server=.;Initial Catalog=TestDb;Integrated Security=true;MultipleActiveResultSets=True;")
{
}
public DbSet<Person> Peoples { get; set; }
// add poco classes here
}

创建您的custom身份 POCO:

public class User : IdentityUser<Guid, UserLogin, UserRole, UserClaim>
public class Role : IdentityRole<Guid,UserRole>
public class UserLogin : IdentityUserLogin<Guid>
public class UserRole : IdentityUserRole<Guid>
public class UserClaim : IdentityUserClaim<Guid>

现在您有一个 DbContext,可以删除IdentiyMode.cs

执行以下命令:Add-Migration initUpdate-Database --verbose

你不需要其他 DbContext

IdentityContext继承DbContext

public class IdentityDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, 
TUserClaim> : DbContext

因此,如果您确实需要两个 DbContext(我很好奇为什么(,您必须为每个数据库上下文单独启用迁移。并且您必须为每个要生成的配置.cs文件指定一个文件夹。像这样:

PM> Enable-Migrations -ContextTypeName ApplicationDbContext -MigrationsDirectory MigrationsApplicationDbContext
Checking if the context targets an existing database...
Code First Migrations enabled for project SomeWebApplication.
PM> Enable-Migrations -ContextTypeName YourCustomDbContext -MigrationsDirectory MigrationsYourCustomDbContext
Checking if the context targets an existing database...
Code First Migrations enabled for project SomeWebApplication.

您的上下文可能指向同一个数据库(它们可以有一个公共连接字符串(,只要它们不引用同一个表。

是的,您可以将 IdentityModel 移动到另一个文件夹,但您必须手动更改命名空间。(或者获得ReSharper,它会自动完成(

最新更新