Entity framework provides great flexibility to update data in the same datacontext
Dim personA = (from p in datacontext.Person where p.PersonID = 1 select p)
personA.name = txtName.value
datacontext.savechanges()
If I have to move this Update function to Service layer which only takes "Person" in the request, what would be the best way to assign my "Person" request object into the datacontext without doing the deep copying again?
You need to attach your entity object to a data context.
You also need to extend your data context partial class with the AttachUpdeted method. As when you attach a object to a data context it does not know that updates have been made. The code below will tell the data context every property has been updated and needs to be written to the database.
public static void Save(EntityObject entity)
{
using(MyContext ctx = new MyContext)
{
ctx.AttachUpdated(entity);
ctx.SaveChanges();
}
}
public static void AttachUpdated(this ObjectContext obj, EntityObject objectDetached)
{
if (objectDetached.EntityState == EntityState.Detached)
{
object original = null;
if (obj.TryGetObjectByKey(objectDetached.EntityKey, out original))
obj.ApplyPropertyChanges(objectDetached.EntityKey.EntitySetName, objectDetached);
else
throw new ObjectNotFoundException();
}
}
article 1
article 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With