I have a WebApi application and i am working on some POST/PUT methods and i am trying to figure out the optimal way of updating a record in the database using entity framework.
The main issue with using WebApi is the request will only have a subset of the full properties of the full object.
For instance, i have a Site
object that has a Project
navigation object that points to the related project. As currently sites cannot move projects, i don't supply the projectId with the PUT command meaning that Project
object of Site
is empty, which causes issues when trying to update (even when stating that that property is not modified), so i have been forced to reading the record first and then merging the changes and then persisting, like:
Clarity for the example below, site is the object passed as a parameter to the PUT route so in this case is the partial Site object
//Grab the existing site
var dbSite = (from s in _repo
where s.Id == id
select s).FirstOrDefault();
//Update unchanged values
site.Id = id;
site.CreatedOn = dbSite.CreatedOn;
var entry = _uow.Entry(dbSite);
entry.Property(e => e.Code).IsModified = true;
entry.Property(e => e.Active).IsModified = true;
entry.Property(e => e.CreatedOn).IsModified = false;
_uow.Entry(dbSite).CurrentValues.SetValues(site);
//Commit
_uow.Commit();
Is there a way with taking a partial object (without certain navigation properties set) and updating the database without loading it first, or is the best approach loading it and updating the way i am doing it currently?