【问题标题】:Update a List<Entity> in EF4在 EF4 中更新 List<Entity>
【发布时间】:2012-02-23 13:23:52
【问题描述】:

我正在尝试使用 EF4 更新内容列表。但是我还没有找到一种方法来做到这一点。我目前的代码如下:

db.NotifContents.MergeOption = MergeOption.NoTracking;
List<NotifContent> notifContentList = db.NotifContents
     .Where(u => u.FKID_Contact == contactId && !u.Sent && u.CanSendMail)
     .ToList();

List<NotifContent> newNotifContentList = new List<NotifContent>();

foreach(NotifContent notifContent in notifContentList)
{
    notifContent.NextMailSend = dtNextMailSend;        newNotifContentList.Add(notifContent);
    try
    {
        //db.CreateObjectSet<NotifContent>().Attach(notifContent);
        //db.ObjectStateManager.ChangeObjectState(notifContent, System.Data.EntityState.Modified);

        db.AddToNotifContents(notifContent);
        ObjectStateEntry notifContentsEntry = db.ObjectStateManager
            .GetObjectStateEntry(notifContent);
        notifContentsEntry.ChangeState(EntityState.Modified);

        db.SaveChanges();

    }
    catch (Exception exc)
    {
    }
}

但是第二次更新总是会失败,这是可以理解的,因为实体是附加到数据上下文的。

如何在 EF4 中进行批量更新?

更新

如下改变循环

            foreach(NotifContent notifContent in notifContentList)
        {
            notifContent.NextMailSend = dtNextMailSend;
            db.NotifContents.Attach(notifContent);
            db.ObjectStateManager.ChangeObjectState(notifContent, EntityState.Modified);
        }

        db.SaveChanges();

我收到以下错误:-

ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象。

【问题讨论】:

  • db.AddToNotifContents 是做什么的?
  • 它将实体添加到集合中?
  • 对不起,当然是对象上下文上的生成方法。
  • 我认为你需要先detach你的notifContent
  • GertArnold 如您所见解决了我自己的问题 :) 非常好的 EF 扩展!

标签: entity-framework c#-4.0 entity-framework-4 linq-to-entities


【解决方案1】:

我已经下载了 EntityFramework.Extended 库,并且有一个名为 .Update 的方法可以进行批量更新

所以我解决如下:-

            var notifContents =
            db.NotifContents.Where(u => u.FKID_Contact == contactId && u.Sent == false && u.CanSendMail);
        db.NotifContents.Update(notifContents, u => new NotifContent{NextMailSend = dtNextMailSend});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    相关资源
    最近更新 更多