11

我試圖創建一個一對一的關係使用C#在實體框架6使用ASP.NET MVC 5內置用戶身份驗證。如何在ASP.NET MVC 5實體框架6中使用流暢的API映射表?

我能夠使用實體框架創建的默認值創建表和連接。但是,當我嘗試使用流利的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. 

我的代碼:

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

_has沒有定義關鍵字_什麼不明白你? 「IdentityUser」的外觀是什麼? –

回答

18

發生錯誤的原因是派生標識表在派生上下文中具有映射。這需要在新的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()); 
} 
+1

這讓我明白瞭解決方案。謝謝! –

7

它看起來像你缺少你的DbContext到base.OnModelCreating通話。