2014-02-17 77 views
0

我有以下方法:如何使用Entity Framework更新具有外鍵引用的表?

public static Int32 SaveAgent(IAgent i) 
    { 
     dc = new mcollectorDataContext(ConnectionString.GetConStr()); 

     //check if the record exists 
     t_agent matchID = dc.t_agents.Where(x => x.id == i.AgentID).FirstOrDefault(); 

     try 
     { 
      if (matchID == null) 
      { 
      // if not exists add new row 
       t_agent _agent = new t_agent 
       { 
        wallet = i.Wallet, 
        branchid = GetBranchID(i.Branch), 
        lastupdated = i.LastUpdated, 
       }; 
        dc.t_agents.InsertOnSubmit(_agent); 
        dc.SubmitChanges(); 
        return _agent.id; 
      } 
      else 
      { 
       // else update row 
       matchID.wallet = i.Wallet; 
       matchID.branchid = GetBranchID(i.Branch); 
       matchID.lastupdated = i.LastUpdated; 

       dc.SubmitChanges(); 
       return i.AgentID; 
      } 

     } 
     catch (Exception) 
     { 
      throw ; 
     } 
    } 

這種方法保存新REORD但是當我嘗試更新,它失敗了,沒有記錄可以被更新,但它不也拋出一個錯誤。 如何解決這個問題?

+0

那麼錯誤是什麼? – Shoe

+0

沒有錯誤返回,只是更新不反映數據庫中的t =。 @Shoe – Djama

回答

0

也許嘗試告訴實體框架該模型已被修改?

嘗試調用的SubmitChanges

之前加入此

dc.Entry(matchID).STATE = EntityState.Modified;

+0

我不能得到DC的Entry()方法。我已經導入system.Data.Entity但不工作。 – Djama

+0

你使用的是什麼版本的實體框架?我知道在版本4中,你將不得不做這樣的事情dc.ObjectStateManager.ChangeObjectState(matchID,System.Data.EntityState.Modified); –

+0

我正在使用4.5版本 – Djama

相關問題