gpt4 book ai didi

c# - EF如何更新包含实体列表的实体

转载 作者:行者123 更新时间:2023-11-30 12:57:36 25 4
gpt4 key购买 nike

我有一个 Device 类,如下所示。

public class Device
{
public string id { get; set; }
public string name { get; set; }
public List<Instructions> Instructions { get; set; }
}

现在我有一个 View ,其中包含与设备相关的部分以及向设备添加指令的规定。

如果设备是新设备,则 this.context.Devices.Add(device) 工作正常。

但如果我想编辑设备。我是通过id找的。它人口稠密。如果我更改单个属性,那么它运行良好。但我想立即更新整个设备,但这并没有发生。

我的示例代码如下。

public async Task<bool> AddInstrument(Device device)
{
try
{
var newDevice = this.context.Device
.Where(i => i.Id == device.Id).FirstOrDefault();// i tried find,single or default also

//adding new device
if (newDevice == null)
{
this.context.Device.Add(device);
return await this.context.SaveChangesAsync() > 0;
}

//if editing the device
newDevice = device;
return await this.context.SaveChangesAsync() > 0;
}
catch
{
throw;
}
}

我想要达到的目标。

问题:- 我想更新数据库中的相应设备。连同说明。例如以前名为“D22”的设备有 3 条指令(a1、a2、a3)。

但现在同一设备的值名称为“D22_1”,现在指令为 a1、a3(更新任何字段)、a2(删除)。添加了 b1 和 a4,因此在编辑字段后,我将 Instructions as a1,a2,b1,b4 for D22_1 。

我的努力:-

我尝试过的。

1) 对于主设备 D22,如果我明确指定属性就没问题,例如

device.Name="aaaaa";

this.context.savechanges();

将其反射(reflect)在数据库中。我还没有尝试更新列表中的指令。

2)我尝试使用

this.context.Entry(device).State = EntityState.Modified;

但是经过各种点击和试用,我无法运行它。我能得到的最好的是这个错误“这可能发生在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,如果图中的任何实体具有冲突的键值。这可能是因为一些实体是新的,还没有收到.."

请给我一些建议。此外,我想了解与在 EF 中使用列表更新条目相关的各种技术。我假设 EF 会自动处理子对象(即添加/更新和删除)。在我的例子中,设备说明。

最佳答案

试试这个:

this.context.Attach(device);
this.context.Entry(device).State = EntityState.Modified;
this.context.SaveChangesAsync();

关于c# - EF如何更新包含实体列表的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33459688/

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