在使用ApplicationDbContext时解决“没有定义密钥”错误的方法是使用OnModelCreating。
在使用ApplicationDbContext时解决“没有定义密钥”错误的方法是使用OnModelCreating。
我一直在尝试为我的集合类型创建导航属性,我在这个例子中找到了一个人使用OnModelCreating成功实现的方法。我在我的MVC 5应用程序中尝试了一下,但在尝试更新数据库时收到了以下错误:
在模型生成过程中检测到一个或多个验证错误:
BlogEngine.Models.IdentityUserLogin: 实体类型'IdentityUserLogin'没有定义主键。请为该实体类型定义主键。
BlogEngine.Models.IdentityUserRole: 实体类型'IdentityUserRole'没有定义主键。请为该实体类型定义主键。
IdentityUserLogins: 实体集'IdentityUserLogins'基于类型'IdentityUserLogin',该类型没有定义主键。
IdentityUserRoles: 实体集'IdentityUserRoles'基于类型'IdentityUserRole',该类型没有定义主键。
如何解决这些“未定义主键”错误?
我进行了一些搜索,我发现这个解决方案是为了解决一个用户的问题,但他的需求与我的不同。对于我想要做的事情,解决方案似乎过于复杂。
导致问题的代码如下:
public class ApplicationDbContext : IdentityDbContext{ public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } //public DbSet Images { get; set; } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public DbSet Posts { get; set; } public DbSet Images { get; set; } public DbSet Albums { get; set; } public DbSet Tags { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity (). HasOptional(e => e.Tags). WithMany(). HasForeignKey(m => m.Tags_Id); modelBuilder.Entity (). HasOptional(e => e.Posts). WithMany(). HasForeignKey(m => m.Posts_Id); } }
这是我的两个模型之间的多对多关系:
更新以显示IdentityUser:
public class ApplicationUser : IdentityUser { public async TaskGenerateUserIdentityAsync(UserManager manager) { // 注意,authenticationType必须与CookieAuthenticationOptions.AuthenticationType中定义的相匹配 var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // 在这里添加自定义用户声明 return userIdentity; } }
在使用`OnModelCreating`方法时,解决"No key Defined"错误的原因可能是你在该方法中删除了对`base`类的调用。尝试添加如下代码来解决该问题:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //Your configuration goes here }
在这个方法中,`base.OnModelCreating(modelBuilder)`将调用基类的`OnModelCreating`方法,确保正确的初始化和配置。通过添加这行代码,你可以解决"No key Defined"错误。
当在使用 ApplicationDbContext 的 OnModelCreating 方法时出现 'No key Defined' 错误,可能需要添加以下内容:
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId); modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id); modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
参考链接:
- [Map tables using fluent api in asp.net MVC5 EF6?](https://stackoverflow.com/questions/19474662)
- [User in Entity type MVC5 EF6](https://stackoverflow.com/questions/19913447)