[英]Updating existing entities in Entity Framework 6 code-first
我在更新实体框架6中的现有实体时遇到问题。
我的通用更新方法如下:
public virtual void Update(T entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
_context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
_context.SaveChanges();
}
构造函数在哪里:
protected IContext _context;
protected IDbSet<T> _dbset;
public EntityService(IContext context)
{
_context = context;
_dbset = _context.Set<T>();
}
IContext
基本上是DbContext
的接口。
现在,当尝试更新时,出现以下错误;
InnerException = {“ UPDATE语句与FOREIGN KEY约束\\” FK_dbo.Appointment_dbo.Driver_DriverID \\“发生冲突。冲突发生在数据库” DEVDB \\“,表\\” dbo.Driver \\“的列'id'中。 \\ n该语句已终止。“}
现在,类(为简洁起见而减少)为:
public partial class Appointment : AuditableEntity<int>
{
public override int ID { get; set; }
[ForeignKey("AppointmentType")]
public int AppointmentTypeID { get; set; }
public virtual AppointmentType AppointmentType { get; set; }
[ForeignKey("AppointmentStatus")]
public int AppointmentStatusID { get; set; }
public virtual AppointmentStatus AppointmentStatus { get; set; }
[ForeignKey("Driver")]
public int? DriverID { get; set; }
public virtual Driver Driver { get; set; }
[ForeignKey("Vehicle")]
public int? VehicleID { get; set; }
public virtual Vehicle Vehicle { get; set; }
}
现在,我尝试通过两个实体传递结果。
即VehicleID = 1,Vehicle = null,VehicleID = null,Vehicle = VehicleEntity,以及一起。
请参见实体内容示例的屏幕截图:
请问为什么会发生这种情况?
发生DriverID
是因为DriverID
为0
,但是数据库中没有ID为0
Driver
。 由于DriverID
是可为空的,所以您可能会放弃使用DriverID
为null
除非在调用Update
方法之前先了解会发生什么,否则我无法对此进行详细说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.