【发布时间】: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