2015-07-02 73 views
3

數據庫關係看起來像這樣的時刻: http://i.imgur.com/954gPnl.pngC#實體框架 - 初學者

我有所謂的友情連接器表,其中包含2個值和密鑰ID。這個表格描述X個朋友Y,但是Y可能不是朋友X.所以這是某種線性的東西。

我想模擬實體框架一樣,但我不能所有的時間,因爲我得到這個錯誤:

may cause cycles or multiple cascade paths.

我在EF做了兩個表:

class Friendship 
{ 
    [Key] 
    public int id { get; set; } 
    public int whoid { get; set; } 
    public int whomid { get; set; } 

    [ForeignKey("whoid")] 
    public virtual Person who { get; set; } 

    [ForeignKey("whomid")] 
    public virtual Person whom { get; set; } 
} 

class Person 
{ 
    [Key] 
    public int id { get; set; } 
    public string username { get; set; } 
    public string password { get; set; } 
    public string name { get; set;} 
    public string city { get; set; } 
    public string street { get; set; } 
    public string hnum { get; set; } 
    public string bday { get; set; } 

    [InverseProperty("who")] 
    public virtual List<Friendship> wholist { get; set; } 

    [InverseProperty("whom")] 
    public virtual List<Friendship> whomlist { get; set; } 
} 
+0

看看這個:http://stackoverflow.com/questions/26930715/entity-framework-code-first-how-to-map-multiple-self-referencing-many-to-many-r – jlvaquero

回答

0

在的EntityFramework你不能添加多於一個相同類別的外鍵,乳清它得到錯誤..刪除任何此....

[ForeignKey("whoid")] 
public virtual Person who { get; set; } 

[ForeignKey("whomid")] 
public virtual Person whom { get; set; } 

我認爲你在sqlserver中添加時也會遇到這個問題

2

我認爲你需要編寫如下的代碼並添加正確的關係。

class Friendship 
{ 
    [Key] 
    public int id { get; set; } 

    [ForeignKey("who")] 
    public int whoid { get; set; } 

    [ForeignKey("whom")] 
    public int whomid { get; set; } 


    public virtual Person who { get; set; } 


    public virtual Person whom { get; set; } 
} 

class Person 
{ 
    [Key] 
    public int id { get; set; } 
    public string username { get; set; } 
    public string password { get; set; } 
    public string name { get; set;} 
    public string city { get; set; } 
    public string street { get; set; } 
    public string hnum { get; set; } 
    public string bday { get; set; } 

    [InverseProperty("who")] 
    public virtual List<Friendship> wholist { get; set; } 

    [InverseProperty("whom")] 
    public virtual List<Friendship> whomlist { get; set; } 
} 

此外,您還需要在數據庫上下文文件中爲實體之間的關係添加以下代碼。

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
     base.OnModelCreating(modelBuilder); 

     modelBuilder.Entity<Friendship>() 
        .HasRequired(e => e.who) 
        .WithMany(t => t.wholist) 
        .HasForeignKey(e => e.whoid) 
        .WillCascadeOnDelete(false); 

     modelBuilder.Entity<Friendship>() 
        .HasRequired(e => e.whom) 
        .WithMany(t => t.whomlist) 
        .HasForeignKey(e => e.whomid) 
        .WillCascadeOnDelete(false); 




} 
+0

作爲儘管我試圖保存更改,但deubugger顯示一個異常: 「INSERT語句與FOREIGN KEY約束衝突」FK_dbo.Friendships_dbo.People_whoid「 –

+0

此原因背後是在子表上插入記錄時父表上的引用列的值尚不存在。 – Dharmesh