Lea*_*ner 5 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; }
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个视图,其中包含与设备相关的部分以及向设备添加指令的规定。
如果设备是新的,则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;
}
}
Run Code Online (Sandbox Code Playgroud)
我想要实现什么。
问题:- 我想更新数据库中相应的设备。以及说明。例如,以前名为“D22”的设备有 3 条指令(a1、a2、a3)。
但现在同一设备的值名称为“D22_1”,现在指令为 a1、a3(更新任何字段)、a2(删除)。添加了 b1 和 a4,因此在编辑字段后,我将 D22_1 的说明设为 a1,a2,b1,b4 。
我的努力:-
我已经尝试过了。
1)对于主设备D22,如果我明确指定属性就可以了,例如
device.Name="aaaaa";
this.context.savechanges();
Run Code Online (Sandbox Code Playgroud)
将其反映在数据库中。我还没有尝试过用这个来更新列表中的说明。
2)我尝试使用
this.context.Entry(device).State = EntityState.Modified;
Run Code Online (Sandbox Code Playgroud)
但经过各种打击和尝试,我无法运行它。我能得到的最好结果是这个错误“如果图中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。这可能是因为某些实体是新的,尚未收到..”
请给我建议一些东西。此外,我想了解与更新 EF 中的列表条目相关的各种技术。我假设 EF 将自动处理子对象(即添加/更新和删除)。就我而言,设备说明。
尝试这个:
this.context.Attach(device);
this.context.Entry(device).State = EntityState.Modified;
this.context.SaveChangesAsync();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7939 次 |
| 最近记录: |