Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update object with no data contexts

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?

like image 679
tc. Avatar asked Feb 04 '23 13:02

tc.


1 Answers

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

like image 123
TonyAbell Avatar answered Feb 07 '23 17:02

TonyAbell