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

Bob*_*Bob 11 c# entity-framework entity-framework-6 asp.net-mvc-5 asp.net-identity

我正在尝试使用带有内置用户身份验证的ASP.NET MVC 5在Entity Framework 6中使用C#创建一对一的关系.

我能够使用Entity Framework创建的默认值创建表和连接.但是当我尝试使用流畅的API时...更具体地说,当我在模型创建上使用甚至是空的时,我使用包管理器控制台迁移数据库将失败.我如何映射我的一对一关系?

我的错误:

//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.
Run Code Online (Sandbox Code Playgroud)

我的代码:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Cas*_*ben 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());
}
Run Code Online (Sandbox Code Playgroud)


Hao*_*ung 7

看起来你base.OnModelCreating在DbContext 中缺少一个调用.