实体框架核心-更新嵌套实体

时间:2019-07-24 19:23:47

标签: c# entity-framework

给出这两个类:

public class Device {
   public int DeviceId { get; set;}
   public string Name { get; set;}
   public virtual DeviceType DeviceType { get; set;}
}

public class DeviceType {
   public int DeviceTypeId { get; set;}
   public string Name { get; set;}
}

并假设我通过以下方式从数据库获取设备:

var device = context.Devices.Include(d => d.DeviceType).FirstOrDefault();

如何更新所选设备的设备类型?

我一直在尝试以下方式:

device.DeviceType = new DeviceType { DeviceTypeId = 1 };
context.SaveChanges();

但是这不起作用,并给我以下错误:

System.InvalidOperationException: 'The instance of entity type 'DeviceType' 
cannot be tracked because another instance with the key value '{DeviceTypeId: 1}' 
is already being tracked. When attaching existing entities, ensure that only one 
entity instance with a given key value is attached.'

编辑 按以下方式工作

context.Entry<Device>(device).Property<int?>("DeviceTypeId").CurrentValue = 1;

但这并不那么优雅。我想知道是否有更好的方法。

0 个答案:

没有答案