views:

772

answers:

2

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?

+5  A: 

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

TonyAbell
A: 

Is it possible to do this with Linq to SQL classes?

Zarko