gpt4 book ai didi

c# - EntityFramework.dll 中出现“System.Data.Entity.Infrastructure.DbUpdateException”

转载 作者:太空狗 更新时间:2023-10-29 22:02:15 24 4
gpt4 key购买 nike

我写了一个相当简单的代码(基于 WCF 和 Windows 窗体的客户端服务器)。我试图更新数据库以便测试我的代码,但遇到了上述异常。有什么解决办法吗?

      // For testing 
public void updateTable()
{
using (var db = new overlayDBEntities())
{
var overlaydb = new overlayData
{
DeviceId = "1111",
TimestampUTC = new DateTime(1990, 1, 1, 9, 9, 9),
OverlayData1 = "Random Text"
};

db.overlayData.Add(overlaydb);

try
{
db.SaveChanges();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
var overlaydb1 = new overlayData
{
DeviceId = "1111",
TimestampUTC = new DateTime(2000, 2, 2, 10, 10, 10),
OverlayData1 = "seconed seconed seconed "
};

db.overlayData.Add(overlaydb);

try
{
db.SaveChanges();
}
catch (Exception ec)
{
Console.WriteLine(ec.Message);
}
}
}

最佳答案

如果你需要更新数据库中已经存在的行,那么不要使用 context.Add();你可以按如下方式使用。

    var overlaydb1 = new overlayData
{
DeviceId = "1111",
TimestampUTC = new DateTime(2000, 2, 2, 10, 10, 10),
OverlayData1 = "seconed seconed seconed "
};

try
{
db.overlayData.Attach(overlaydb1);
db.ObjectStateManager.ChangeObjectState(overlaydb1, EntityState.Modified);
db.SaveChanges();
}

catch (Exception ec)
{
Console.WriteLine(ec.Message);
}

关于c# - EntityFramework.dll 中出现“System.Data.Entity.Infrastructure.DbUpdateException”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19424058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com