Dan*_*ieu 6 c# entity-framework-6 asp.net-mvc-5 ef-model-builder
我一直想为我的集合类型创建导航属性,我发现这个例子中的一个人如何完成它使用OnModelCreating.我在我的MVC 5应用程序中试了一下,在尝试更新我的数据库时收到了这个错误:
在模型生成期间检测到一个或多个验证错误:
BlogEngine.Models.IdentityUserLogin :: EntityType'IdentityUserLogin'没有定义键.定义此EntityType的键.BlogEngine.Models.IdentityUserRole :: EntityType'IdentityUserRole'没有定义键.定义此EntityType的键.IdentityUserLogins:EntityType:EntitySet'IdentityUserLogins'基于没有定义键的类型'IdentityUserLogin'.IdentityUserRoles:EntityType:EntitySet'IdentityUserRoles'基于类型'IdentityUserRole',没有定义键.
我做了一些搜索,我找到了解决一个用户问题的解决方案,但他的需求与我的不同.对于我想要做的事情,解决方案似乎很复杂.
这是导致问题的代码:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
//public DbSet<Image> Images { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<Post> Posts { get; set; }
public DbSet<Image> Images { get; set; }
public DbSet<Album> Albums { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Post>().
HasOptional(e => e.Tags).
WithMany().
HasForeignKey(m => m.Tags_Id);
modelBuilder.Entity<Tag>().
HasOptional(e => e.Posts).
WithMany().
HasForeignKey(m => m.Posts_Id);
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我与多对多关系的模型:
更新以显示IdentityUser:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
Run Code Online (Sandbox Code Playgroud)
jjj*_*jjj 12
您可能需要添加以下内容 OnModelCreating
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 });
Run Code Online (Sandbox Code Playgroud)
也可以看看:
我认为问题是你已经删除了base类的调用OnModelCreating.尝试添加,如下所示
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//Your configuration goes here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9189 次 |
| 最近记录: |