Reputation: 3941
I have an issue updating an existing entity in Entity Framework 6.
My generic update method is as follows:
public virtual void Update(T entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
_context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
_context.SaveChanges();
}
where the constructor is:
protected IContext _context;
protected IDbSet<T> _dbset;
public EntityService(IContext context)
{
_context = context;
_dbset = _context.Set<T>();
}
IContext
is basically an interface of DbContext
.
Now when trying to update I get the following error;
InnerException = {"The UPDATE statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Appointment_dbo.Driver_DriverID\". The conflict occurred in database \"DEVDB\", table \"dbo.Driver\", column 'id'.\r\nThe statement has been terminated."}
Now the classes (reduced for brevity) are:
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; }
}
Now I have tried passing the result in through both entities.
i.e. VehicleID = 1 with Vehicle = null, VehicleID = null with Vehicle = VehicleEntity, and also together.
See the screenshot of the entity contents example:
Any ideas why this is occurring please?
Upvotes: 1
Views: 138
Reputation: 31206
It's occuring because DriverID
is 0
, but there is no Driver
in the DB with an ID of 0
. Since DriverID
is nullable, you can probably get away with a DriverID
of null
I can't elaborate much more on that unless I see what happens before you call the Update
method.
Upvotes: 2