如何在没有上下文信息更新对象上下文、对象、如何在、信息

2023-09-04 01:47:12 作者:金钱美酒凯子与狗

实体框架提供了很大的灵活性,以更新同一DataContext的数据

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()

如果我要搬到这个更新的功能服务层,只需要人的要求,这将是无需再做深拷贝分配我的人请求对象为在DataContext最好的方法是什么?

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.

您还需要与AttachUpdeted方法扩展您的数据上下文部分类。正如当你连接一个对象到数据上下文不知道更新已经完成。低于code将告诉数据上下文的每个属性已更新,需要被写入到数据库中。

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();
    }
}

第1条 第2条