2017-06-16 63 views
0

我正在使用EF 6.1.3。基本上我有兩類:實體框架 - 插入列創建重複

public class User 
{ 
    public int Id { get; set; } 
} 

public class Card 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public User CreatedBy { get; set; } 
} 

當然,檢查表定義,是CardCreatedByUserId之間建立一個外鍵關係。 Card現在有一個CreatedBy_Id列。

我接種了一個默認User(Id = 1),它存儲在一個變量中,我們將其稱爲CurrentUser。現在,當我想輸入一個卡:

context.Cards.Add(new Card 
{ 
    Name = "Card of Water", 
    CreatedBy = CurrentUser 
}); 
context.SaveChanges(); 

結果我得到的是新Card被創建,但CreatedBy沒有存儲CurrentUser參考。而是創建了一個新的User(Id = 2),這就是存儲在新的CardCreatedBy中的內容。

我該如何解決這個問題?謝謝。

編輯:

CurrentUser在程序的開始時設置的值,在Load事件起始的形式。它被聲明爲一個全局變量:

CurrentUser = context.Users.First(); //In load event 

添加只是爲了測試真的,在一個按鈕。上面的代碼就是它的全部。

+0

從哪裏'CurrentUser'變量來?在這裏發佈完整的代碼,我會幫助你。 –

+0

不會在db中創建關係 –

+0

我可能在這裏是錯誤的,但是因爲'User'有一個int類型的id,所以'Card'類不應該有一個名爲'public int CreatedById {get;組; }'或者什麼,它存儲了創建它的用戶的實際整數ID? –

回答

0
public class User 
{ 
    public int Id { get; set; } 
} 

public class Card 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 

    [ForeignKey("CreatedBy")] 
    public int UserId { get; set; } 

    public User CreatedBy { get; set; } 
} 

context.Cards.Add(new Card 
{ 
    Name = "Card of Water", 
    UserId = CurrentUser.Id, 
    CreatedBy = CurrentUser 
}); 
context.SaveChanges(); 
+0

外鍵不需要在你的實體類中有.. –

0

要解決這個問題,你需要在這兩個表之間和建立以下外鍵關係

public class User 
{ 
    [Key] 
    public int Id { get; set; }   // primary key 
} 

public class Card 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 

    [ForeignKey("CreatedBy")] 
    public int UserId { get; set; } // Foreign Key 

    public virtual User CreatedBy { get; set; } 
    //use virtual keyword to allow lazy loading while execution 
} 

context.Cards.Add(new Card 
{ 
    Name = "Card of Water", 
    UserId = CurrentUser.Id 
    //No need to insert CreatedBy user object here as we are passing UserId 
}); 
context.SaveChanges(); 
+0

外鍵不需要在你的實體類中有.. –

+0

如何獲得'ForeignKey'屬性? – AwonDanag

+0

@JenishRabadiya不需要?怎麼會這樣?你能解釋一下嗎? – AwonDanag