我正在开始一个全新的 .NET MVC 项目,对 EF 6 和 .NET 4.5 使用代码优先。我也想使用 Identity 框架,并在我的项目的上下文配置中扩展 Identity 基类。(不确定我说的是否正确……我是一位经验丰富的 C#/.NET 开发人员,对 MVC、EF 和 Identity 有点陌生。)
我的问题:出了点问题。在尝试生成新迁移时,我收到错误:
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) {}
}
这将建立,但如果没有这些错误,我无法生成迁移,并且由于我对所有细节的知识和理解有限,我感到困惑。