我遇到一个问题,当我尝试使用实体框架6插入一个引用大量现有实体到mydb的新父对象时,它会插入实体而不是链接它们吗?
我有以下课程(为简洁而减少);
public partial class Shipment
{
[JsonProperty(PropertyName = "shipmentid")]
public override int ID { get; set; }
public DateTimeOffset ShipmentDate { get; set; }
public string Carrier { get; set; }
public virtual List<Device> Device { get; set; }
[ForeignKey("ShipmentType")]
[JsonProperty(PropertyName = "shipmenttypeid")]
public int? ShipmentTypeId { get; set; }
public virtual ShipmentType ShipmentType { get; set; }
}
现在你可以看到我与设备列表有1对多的关系。
我想创建一个新的Shipment实例,但我需要链接x个现有设备。
我创建了对象,然后使用post将其传递给我的web api。我已经调试了,设备列表正在通过ok。
我使用通用存储库插入;
public virtual void Insert(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
_dbset.Add(entity);
_context.SaveChanges();
}
我的webapi方法使用以下方法调用它;
_Service.Insert(shipment);
构建对象时,我只是简单地
var shipment = new Shipment();
var device1 = GetDeviceFromWebApi; //psuedo
var device2 = GetDeviceFromWebApi; //psuedo
List<Device> deviceList = new List<Device>();
deviceList.Add(device1);
deviceList.Add(device2);
Shipment.Device = deviceList;
我拍摄了一个简单示例的屏幕截图,其中显示了传递的单个设备。这是在webapi方法的POST中。
有没有办法可以将设备标记为现有设备并告诉EF不要更新(我想假设Device.ID为空或空?)
有人可以帮忙吗?
编辑1
回到CodeCasters回答
public override void Insert(Shipment entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
foreach (var device in entity.Device)
if (device.ID != null && device.ID > 0)
_context.Entry(device).State = EntityState.Unchanged;
_dbset.Add(entity);
_context.SaveChanges();
}
请注意区别是我使用.State而不是EntityState,因为这在我的界面中不存在。
但是当我尝试插入时会出现以下错误?
发生了引用完整性约束违规:关系一端的“Vehicle.ID”的属性值与另一端的“Device.VehicleId”的属性值不匹配。
现在在这种情况下,我在设备上设置了外键。当从数据库中提取设备时,将填充车辆类型,但不填充FK int(使用以下内容;)
public int? VehicleId { get; set; }
public virtual Vehicle Vehicle { get; set; }
我现在是怎么做的?我是否需要获取Vehicle.Id并将其分配给VehicleId?