2017-07-24 114 views
0

我試圖更新名爲(Friendship)的表中的外鍵。外鍵的表名爲(FriendshipStatus)問題是所有的值都被更新,除了外鍵。我使用代碼第一的方法。使用實體框架更新外鍵

友誼類

public class Friendship 
{ 
    public int Id { get; set; } 
    public User UserOne { get; set; } 
    public User UserTwo { get; set; } 
    public FriendshipStatus Status { get; set; } 
    public User ReqSB { get; set; } 
    public RelationType RelationType { get; set; } 
    public Relationship Relationship { get; set; } 
    public DateTime FriendshipDate { get; set; } 



} 

FriendshipStatus類

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

這裏是上面的代碼更改爲日期時間更新

using (context) 
     { 


      Friendship f = getFrienshipRecord(u1, u2); // get single record from db which is to be updated 
      if (f != null) 
      { 
       Friendship ff = new Friendship(); 
       ff.Status = new FriendshipStatus() { Id = 2}; //actually wants to update this this field 
       ff.Id = f.Id; 
       ff.FriendshipDate = DateTime.Now; 

       context.Entry(ff).State = EntityState.Modified; 
       context.SaveChanges(); 


      } 

     } 

的代碼,但它不會改變外鍵。

+0

您需要更新FriendshipStatus的狀態以進行修改。另一種方法是更新您提取的記錄(f),而不是創建新實例並設置其狀態。 –

+0

你能告訴我示例代碼,我如何更新FriendshipStatus的狀態進行修改。我嘗試了另一種方式,而不創建新的實例,但同樣的問題。 @SteveGreene – Ali

回答

0

這是我用於包含孩子的更新的技術。首先,我喜歡將外鍵作爲父鍵的一部分。如果你的名字FriendshipStatusId,EF會自動進行關聯,也可以添加註釋或流暢的代碼,如果首選:

public class Friendship 
{ 
    public int Id { get; set; } 
    public User UserOne { get; set; } 
    public User UserTwo { get; set; } 

    public int? FriendshipStatusId { get; set; } // optional FK 
    public FriendshipStatus Status { get; set; } 

    public User ReqSB { get; set; } 
    public RelationType RelationType { get; set; } 
    public Relationship Relationship { get; set; } 
    public DateTime FriendshipDate { get; set; } 
} 

現在,你可以通過簡單地獲取實體(這使它在追蹤)做你的更新和更新FK:

using (context) 
{ 
    Friendship f = getFrienshipRecord(u1, u2); // get single record from db which is to be updated 
    if (f != null) 
    { 
     f.FriendshipDate = DateTime.Now; 
     f.FriendshipStatusId = 2; 
     context.SaveChanges(); 
    } 
} 

請注意,如果你添加FK你可能需要做遷移或重新生成數據庫,因爲EF默認可能是這樣的FriendshipStatus_Id。

+0

Is'nt有沒有簡單的方法來做到這一點?爲什麼它非常複雜:( – Ali

+0

有不同的方法可以做到這一點,簡單是主觀的,我們做了一些不同於上面的代碼的東西,你可以[注入](http://www.davepaquette.com/archive/2013 /03/27/managing-entity-framework-dbcontext-lifetime-in-asp-net-mvc.aspx)上下文,你可以使用[Automapper](https://www.exceptionnotfound.net/entity-framework-and -wcf-mapping-entities-to-dtos-with-automapper /)更新視圖模型中的實體等。你想要簡化哪些部分? –