【问题标题】:update disconnected object in entity framework更新实体框架中的断开连接的对象
【发布时间】:2009-11-11 13:23:24
【问题描述】:

我有一些来自其他层的数据,它代表一个 EF 对象。 当它是新的时,我会这样做:

context.AddToCustomer(mynewobject);
context.SaveChanges();

但现在我的数据形成了一个现有对象,所以我希望上下文知道我想要更新数据而不是插入它。

我看过“ApplyPropertyChanges”,但不知道如何使用它。 我也看到有人这样做:

Customer existingOne = (from n in context.Customers 
                        where n.id = mynewobject.id select n).First()
existingOne.name = mynewobject.name
existingOne.address= mynewobject.address
context.SaveChanges();

但这似乎有点奇怪,因为我必须手动设置所有道具并首先读取整个对象。

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    在 Entity Framework 5 中,这就是你的工作方式:

            /// <summary>
            /// Updates an entity
            /// </summary>
            /// <param name="input">A entity</param>
            /// <returns>The updated object</returns>
            public TEntity Update(TEntity input)
            {
                using (var context = GetContext())
                {
                    context.Set<TEntity>().Attach(input);
    
                    var entry = context.ChangeTracker.Entries<TEntity>().FirstOrDefault(e => e.Entity == input);
                    if (entry != null)
                        entry.State = EntityState.Modified;
    
                    context.SaveChanges();
                }
    
                return input;
            }
    

    【讨论】:

      【解决方案2】:

      虽然我质疑“优化”更新是否值得,但您仍然可以按照您的要求去做。 It's easier in EF 4,还有possible in EF 1。另见this article

      public static void AttachAsModified<T>(this ObjectSet<T> objectSet, T entity) where T : class
      {
          objectSet.Attach(entity);
          objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
      }
      

      【讨论】:

      • 只是补充一点,当您想更新其他属性而不是标量时,使用 EF1 会变得更复杂(正如您将能够在“EF1 中可能”的“警告”部分看到的那样)文章)。您可以在此问题的答案stackoverflow.com/questions/1612655/… 之间找到解决方法
      • 非常感谢您的回答。有时你只需要看到它就可以相信它。我自己也想不通,“EF 1 中的可能”解决方案。
      【解决方案3】:

      我的post 中有一个可以执行此操作

      【讨论】:

        【解决方案4】:

        取自Employee Info Starter Kit,可以考虑如下代码sn-p:

        public void UpdateEmployee(Employee updatedEmployee)
                {
                    //attaching and making ready for parsistance
                    if (updatedEmployee.EntityState == EntityState.Detached)
                        _DatabaseContext.Employees.Attach(updatedEmployee);
                    _DatabaseContext.ObjectStateManager.ChangeObjectState(updatedEmployee, System.Data.EntityState.Modified);
                    _DatabaseContext.SaveChanges();
                }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-03-13
          • 1970-01-01
          • 1970-01-01
          • 2018-05-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多