简体   繁体   中英

Updating existing entities in Entity Framework 6 code-first

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.

ie 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM