You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Entity Framework中SaveChanges无法生效问题求助

问题:EF更新数据偶尔失效,无报错但日志正常写入

问题场景

执行以下C#代码尝试更新数据库表时,Writelog函数能正常写入"Updated"日志,但Cl表的目标字段并未更新,且数据偶尔会成功更新,全程无任何报错信息。

using (var dbcontext = new EVEntities())
{
    var data_header = dbcontext.Cl.Where(x => x.PKey == 
        header_key).FirstOrDefault();
    if (data_header != null)
    {
        data_header.EstimatedCost = Math.Round(estimated_cost,2);
        data_header.ClaimedCost = Math.Round(claimed_cost,2);
        dbcontext.Entry<Cl>(data_header).State = System.Data.Entity.EntityState.Modified;
        dbcontext.SaveChanges();
        Writelog("Updated");
    }
}

数据库连接字符串

<connectionStrings><add name="EVEntities" connectionString="metadata=res://*/xxx_Entity_Model.csdl|res://*/xxx_Entity_Model.ssdl|res://*/xxx_Entity_Model.msl; provider=System.Data.SqlClient;provider connection string=&quot;data source=xxxxxx;initial catalog=xxxxx;persist security info=True;user id=xx;password=xxxxx;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient"/></connectionStrings>

补充尝试(Edit1)

改用原生SQL更新语句后,问题依旧:数据偶尔更新成功,无报错,日志正常写入。

dbcontext.Database.ExecuteSqlCommand(@"UPDATE dbo.Claims 
SET EstimatedCost = @e_cost, ClaimedCost = @c_cost WHERE Pkey =
 @p_key",
new SqlParameter("e_cost", Math.Round(estimated_cost, 2)),
new SqlParameter("c_cost", Math.Round(claimed_cost, 2)),
new SqlParameter("p_key", claim_header_key));

内容的提问来源于stack exchange,提问作者Sachu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:35:36