如何在ASP.NET MVC 5,Entity Framework 6中使用流畅API映射表?

11
我正在尝试使用C#在Entity Framework 6中创建一对一关系,并使用内置的用户身份验证ASP.NET MVC 5。我能够使用Entity Framework创建默认的表和连接。但是,当我尝试使用流畅的API时......更具体地说,当我使用on model creating事件甚至是空的数据库迁移时,使用包管理器控制台将失败。如何映射我的一对一关系?
我的错误:
//error
//my.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined.   //Define the key for this EntityType.
//my.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.

我的代码:

namespace my.Models
{

    public class ApplicationUser : IdentityUser
    {
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }

        public DbSet<EngineeringProject> EngineeringProjects { get; set; }

        public DbSet<EngineeringProject> EngineeringDesigns { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new EngineeringDesignMap());
            modelBuilder.Configurations.Add(new EngineeringProjectMap());
        }

    }
}

namespace my.Models.Mapping
{
    public class EngineeringProjectMap : EntityTypeConfiguration<EngineeringProject>
    {
        public EngineeringProjectMap()
        {
            this.HasRequired(t => t.EngineeringPd)
                .WithOptional(t => t.EngineeringProject);
            this.HasRequired(t => t.EngineeringProjectCategory)
                .WithMany(t => t.EngineeringProjects)
                .HasForeignKey(d => d.CategoryId);
        }
    }
}

没有定义键。你不清楚吗?IdentityUser是什么样子的? - Gert Arnold
2个回答

19

错误发生是因为派生标识表在衍生上下文中具有映射。这需要在新的OnModelCreating重写函数中调用。要做到这一点,只需在您的方法中添加base.OnModelCreating(modelBuilder),如下所示。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    base.OnModelCreating(modelBuilder); // <-- This is the important part!
    modelBuilder.Configurations.Add(new EngineeringDesignMap());
    modelBuilder.Configurations.Add(new EngineeringProjectMap());
}

7

看起来您的DbContext中缺少对base.OnModelCreating的调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接