2017-10-13 107 views
0

我意外刪除了我的數據庫的幾個表,並設法恢復它的一些部分。實體框架代碼 - 第一次重新創建外鍵約束

但似乎我的外鍵不是在添加新的遷移並運行update-database命令後創建的。

規範缺失外鍵約束缺失:

modelBuilder.Entity<File.File>() 
     .HasRequired(f => f.FileType) 
     .WithMany() 
     .WillCascadeOnDelete(false); 

modelBuilder.Entity<File.FileType>() 
     .HasMany(a => a.ApplicationUsers) 
     .WithMany(a => a.FileTypes); 

是否有利用二維碼的第一個我可以重新創建密鑰的方法嗎? PS:我試圖運行'update-database -force',但它沒有解決我的問題。

PS2:這是我的測試數據庫,如果你想知道,但我想學習如何解決這個問題。

+0

你有,你想保持數據庫的數據? –

+0

modelBuilder.Entity () .HasRequired(f => f.FileType) .WithMany() .WillCascadeOnDelete(false);這裏withmany應該有一個代表一對多關係的實體 –

回答

0

進入一對多的關係,您需要添加:

.HasForeignKey(f => f.Id_Representation_In_Foreign_Table) 

多對多的關係:

  .HasMany(i => i.ApplicationUsers) 
      .WithMany(i => i.FileTypes) 
      .Map(m => // use map if you're overwriting convention, otherwise sql will create name of the columns automatically 
      { 
       m.ToTable("FileTypesAndSmth"); 
       m.MapLeftKey("ApplicationUserId"); 
       m.MapRightKey("FileTypeId"); 
      });