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

5
我有一个名为 Device 的类,如下所示。
public class Device
{
    public string id { get; set; }
    public string name { get; set; }
    public List<Instructions> Instructions { get; set; }
}

现在我有一个视图,其中包含与设备相关的部分,并提供向设备添加指令的机会。
如果设备是新的,则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”的设备有三个说明(a1、a2、a3)。
但是现在同一设备具有名称“D22_1”,现在说明是a1、a3(更新任何字段)、a2(删除)。b1和a4被添加,因此在编辑字段后,我有了D22_1的说明a1、a2、b1、b4。
我的努力:
我尝试过以下内容。
1)对于主设备D22,如果我明确指定属性,则可以正常运行,例如:
device.Name="aaaaa";

this.context.savechanges();

将英语翻译成中文:

将其反映在数据库中。我尚未尝试过在列表中更新说明。

2)我尝试使用

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

但是我尝试了许多次都无法运行它。我能得到的最好结果是这个错误:“当使用“Attach”方法或将实体的状态设置为“未更改”或“已修改”时,如果图中的任何实体具有冲突的键值,则可能会发生此情况。这可能是因为某些实体是新的,尚未接收...”
请给我一些建议。此外,我想了解与在EF中使用列表更新条目相关的各种技术。我假设EF将自动处理子对象(即添加/更新和删除)。
在我的情况下,这是设备说明。

这篇帖子展示了如何更新实体的集合。基本上,它循环遍历集合中的项目,并处理可能发生的三种情况——项目添加、项目更新、项目删除。 - Martin Staufcik
1
newDevice = device; 这是问题所在:newDevice 在上下文中,而 device 不在。由于你将引用设置为另一个值,EF 无法再跟踪它。你需要逐个设置属性或者在分离的场景中工作。 - DevilSuichiro
@DevilSuichiro,我该如何实现这个?在分离的场景下工作。 - Learner
1个回答

0

试试这个:

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

我遇到了这个错误。附加类型为“Device”的实体失败,因为另一个具有相同主键值的实体已经存在。当使用“Attach”方法或将实体状态设置为“Unchanged”或“Modified”时,如果图中的任何实体具有冲突的键值,则可能会发生这种情况。这可能是因为某些实体是新的,并且尚未接收到数据库生成的键值。在这种情况下,请使用“Add”方法或“Added”实体状态来跟踪图形,然后根据需要将非新实体的状态设置为“Unchanged”或“Modified”。 - Learner
我尝试了这个:-this.context.Device.Attach(newDevice); newDevice = device; this.context.Entry(newDevice).State = System.Data.Entity.EntityState.Modified; - Learner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接