C# EF如何更新包含实体列表的实体
我有一个类设备,如下所示C# EF如何更新包含实体列表的实体,c#,asp.net-mvc,entity-framework,entity-framework-6,asp.net-mvc-5.2,C#,Asp.net Mvc,Entity Framework,Entity Framework 6,Asp.net Mvc 5.2,我有一个类设备,如下所示 public class Device { public string id { get; set; } public string name { get; set; } public List<Instructions> Instructions { get; set; } } public async Task<bool> AddInstrument(Device device) { try {
public class Device
{
public string id { get; set; }
public string name { get; set; }
public List<Instructions> Instructions { get; set; }
}
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;
}
}
我想要达到的目标
问题:-我想更新数据库中相应的设备。和说明书一起。
e、 g.以前,名为“D22”的设备有3条指令(a1、a2、a3)
但现在同一个设备的值名为“D22_1”,现在的指令是a1、a3(更新任何字段),a2(删除)。b1和a4被添加,因此在编辑字段后,我有a1、a2、b1、b4等D22_1的说明
我的努力:
我已经试过了
1) 对于主设备D22,如果我明确指定属性,它是好的,例如
device.Name="aaaaa";
this.context.savechanges();
在数据库中反映它。我还没有尝试过更新列表中的说明
2) 我试着用
this.context.Entry(device).State = EntityState.Modified;
但是由于各种各样的试玩,我无法运行它。我能得到的最好的结果是这个错误“如果图形中的任何实体具有冲突的键值,则在使用'Attach'方法或将实体的状态设置为'Unchanged'或'Modified'时可能会发生这种情况。这可能是因为某些实体是新的,尚未收到..”
请给我提个建议。此外,我想知道与在EF中使用列表更新条目相关的各种技术。我假设EF将自动处理子对象(即添加/更新和删除)。
在我的例子中,设备说明。请尝试以下操作:
this.context.Attach(device);
this.context.Entry(device).State = EntityState.Modified;
this.context.SaveChangesAsync();
谢谢大家。谢谢你给我指路。 我的问题解决了。更新/删除现在工作正常。我现在将调整添加的解决方案。
我利用了这个“演示了如何更新实体的集合。基本上,它通过集合中的项目进行循环,并处理可能发生的三种情况-添加项目、更新项目、删除项目。newDevice=device;这就是问题所在:newDevice在上下文中,device不在上下文中。由于将引用设置为另一个值,EF无法再跟踪它。你必须一个接一个地设置属性,或者在分离的场景中工作。@DevilSuichiro我怎么做?在分离场景中工作,我收到此错误。附加“Device”类型的实体失败,因为相同类型的另一个实体已具有相同的主键值。如果图形中的任何实体具有冲突的键值,则在使用“Attach”方法或将实体状态设置为“Unchanged”或“Modified”时可能会发生这种情况。这可能是因为某些实体是新的,尚未收到数据库生成的键值。在这种情况下,请使用“添加”方法或“添加”实体状态来跟踪图形,然后根据需要将非新实体的状态设置为“未更改”或“已修改”。我尝试了以下操作:-this.context.Device.Attach(newDevice);新设备=设备;this.context.Entry(newDevice).State=System.Data.Entity.EntityState.Modified;