簡體   English   中英

如何使用實體框架更新具有外鍵引用的表?

[英]How to update a table which has a foreign key reference using 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 ;
        }
    }

此方法可以保存新的ordord,但是當我嘗試更新時,它失敗了,無法更新任何記錄,但是它也不會引發錯誤。 如何解決該問題?

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

在致電submitchanges之前嘗試添加它

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM