2016-09-14 57 views
0

我遇到了這個錯誤,因爲標題說。我搜索谷歌,找不到答案,因爲如果我使用sql來插入,這是可以的,當我使用ef來添加時,它無法工作。在下面看,它是我的數據庫模式。 enter image description hereEF:「ReferentialConstraint中的依賴屬性映射到商店生成的列」Id變化

,當我嘗試添加一些好表,誤差occured.the良好的流暢API似乎是這樣的:

using ppdai.user.vip.model; 
using System; 
using System.ComponentModel.DataAnnotations.Schema; 
using System.Data.Entity.ModelConfiguration; 
using System.Data.Entity.ModelConfiguration.Configuration; 

namespace ppdai.user.vip.model.mapping 
{ 
public class GoodsMapping: EntityTypeConfiguration<Goods> 
{ 
    public GoodsMapping() 
    { 
     this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 
     this.HasKey(x => x.Id); 


     this.Property(x => x.GoodsQuantity).IsRequired(); 
     this.Property(x => x.GoodPrice).IsRequired(); 
     this.Property(x => x.GoodScore).IsRequired(); 
     this.Property(x => x.GoodTypeId).IsRequired(); 

     this.HasRequired(x => x.GoodType) 
      .WithMany(x => x.Goods) 
      .HasForeignKey(x => x.GoodTypeId); 


    } 

} 
} 

結果,好的是「中心」表的位置在我的數據庫中,任何人都知道如何解決它?

+0

你用'.HasForeignKey(x => x.GoodTypeId)定義了foregin關鍵字;' –

+0

@AliSoltani它與你提到的沒有任何關係,因爲我把外鍵關掉了,它仍然無法工作。 – MapleStory

回答

1

它看起來像你的一個外鍵列被設置爲數據庫生成。 檢查Goods中的GoodTypeId未設置爲自動遞增的標識。 還請檢查和GoodId中的GoodId中的HomePageProducts

+0

nope,所有的foregin key都不是標識,它與我認爲的foregin key沒有關係,因爲我取消了goods table的foregin key,它仍然觸發相同的異常。如果我將Id設置爲不具有identity屬性,則會說「無法插入,因爲set identity_insert處於關閉狀態」 – MapleStory

+0

您報告的錯誤與主鍵無關,它與外鍵有關。另外,您不必將主鍵設置爲DatabaseGenerated。按照慣例,該鍵將被自動設置爲DatabaseGenerated。檢查其他外鍵,而不僅僅是Goods表中的外鍵。 – sachin

+0

有沒有foregin鍵是由datebase生成的,我仔細檢查了一下,當我使用sql插入時,它可以工作,爲什麼?但是我們不能 – MapleStory

相關問題