【问题标题】:How to update object with no data contexts如何更新没有数据上下文的对象
【发布时间】:2010-09-14 16:31:17
【问题描述】:

实体框架提供了极大的灵活性来更新同一数据上下文中的数据

Dim personA = (from p in datacontext.Person where p.PersonID = 1 select p)
personA.name = txtName.value
datacontext.savechanges()

如果我必须将此更新功能移动到仅在请求中使用“Person”的服务层,那么将我的“Person”请求对象分配到数据上下文而不再次进行深度复制的最佳方法是什么?

【问题讨论】:

    标签: .net vb.net entity-framework


    【解决方案1】:

    您需要将实体对象附加到数据上下文。

    您还需要使用 AttachUpdeted 方法扩展您的数据上下文部分类。当您将对象附加到数据上下文时,它不知道已经进行了更新。下面的代码将告诉数据上下文每个属性都已更新并需要写入数据库。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      相关资源
      最近更新 更多