我开始一个全新的.NET MVC项目,首先针对EF 6和.NET 4.5使用代码。我也想使用Identity框架,并在我的项目的上下文配置中扩展Identity基类。 (不知道我说的都是正确的......我是一位经验丰富的C#/ .NET开发人员,对于MVC,EF和身份来说有点新鲜。)在EF中集成和扩展.NET标识类(代码优先)
我的问题:有些事情是错误的。在试图产生一个新的迁移,我得到错误:
POST.Data.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
POST.Data.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
好了,所以,我在我的项目,一个用于身份类,其他为一切两个上下文。相同的数据库,并且任何上下文都不涉及其他任何内容。我正是如此定义实体:
public class ApplicationUser : IdentityUser { }
public class ApplicationRole : IdentityRole { }
public class ApplicationUserRole : IdentityUserRole { }
public class ApplicationUserClaim : IdentityUserClaim { }
public class ApplicationUserLogin : IdentityUserLogin { }
然后,我有一个上下文类是这样的:
public partial class IdentityContext : IdentityDbContext
{
public IdentityContext() : base() { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(ul => ul.UserId);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(ur => new { ur.RoleId, ur.UserId });
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<ApplicationUserClaim> ApplicationUserClaims { get; set; }
public DbSet<ApplicationUserLogin> ApplicationUserLogins { get; set; }
public DbSet<ApplicationRole> ApplicationRoles { get; set; }
public DbSet<ApplicationUserRole> ApplicationUserRoles { get; set; }
}
不知道它甚至事项,但我的配置事情是这样的:
internal sealed class Configuration : DbMigrationsConfiguration<POST.Data.Models.Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = @"ContextMigrations";
}
protected override void Seed(POST.Data.Models.Context context) {}
}
这将会建立起来,但是如果没有这些错误,我不能产生迁移,并且我对有限的知识和对所有细节的理解都很困惑。
好的,所以这是我正在采取的原始方向,但创建了单独的子类,因为我以为我想在将来扩展它们,我现在也可以让我的生活变得轻松。但是我坦白地说,仅仅让它独自存在就是一种逻辑。 –
但我有这个问题,我希望我正确地说出这个问题:如果我没有一个从IdentityDbContext继承的单独的上下文,而是从DbContext继承,那么如何创建基类的Identity类所有这些具体实体将会在我的数据库中生成?我的意思是,在某些时候,我需要说我希望创建AspNet Identity表,对吗?又怎样?我有我的其他背景像MainContext:DbContext;应该是MainContext:IdentityDbContext? –
好的,没关系。我相信我有这个想法...... :-P你只需创建单独的上下文并将其保留为空。 –