How to update object with no data contexts

2020-05-27 14:42发布

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?

1条回答
啃猪蹄的小仙女
2楼-- · 2020-05-27 15:20

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

查看更多
登录 后发表回答