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



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

我做了一些搜索,发现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 });

另请参见:
  • Map tables using fluent api in asp.net MVC5 EF6?
  • User in Entity type MVC5 EF6
  • 关于c# - 解决将OnModelCreating与ApplicationDbContext一起使用时的 'No key Defined'错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30315968/

    10-12 00:11
    查看更多