gpt4 book ai didi

c# - 在将 OnModelCreating 与 ApplicationDbContext 一起使用时解决 'No key Defined' 错误?

转载 作者:太空狗 更新时间:2023-10-29 20:48:20 25 4
gpt4 key购买 nike

我一直在尝试为我的集合类型创建导航属性,我发现了 this example一个人如何使用 OnModelCreating 完成它。我在我的 MVC 5 应用程序中试了一下,在尝试更新我的数据库时收到此错误:

One or more validation errors were detected during model generation:

BlogEngine.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. BlogEngine.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.

如何解决这些“未定义 key ”错误?

我做了一些搜索,找到了 this solution对于一个用户问题,但他的需求与我的不同。这些解决方案对于我正在尝试做的事情来说似乎相当复杂。

这是导致问题的代码:

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);
}

}

这是我的多对多关系模型:

Post.cs model on Gist

Tag.cs model on Gist


更新以显示 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;
}
}

最佳答案

您可能需要向 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 });

另请参阅:

关于c# - 在将 OnModelCreating 与 ApplicationDbContext 一起使用时解决 'No key Defined' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com