【发布时间】:2017-03-06 11:09:18
【问题描述】:
我有列表对象并尝试检查和更新该列表中的这些项目这是我的代码:
using (var uow = new WareHouseUnitOfWork(WareHouseConnection))
{
foreach (var item in lData)
{
if (uow.UsageSessionWareHouseRepository.Contains(x => x.RadAcctRefId == item.RadAcctRefId))
{
uow.UsageSessionWareHouseRepository.Context.Entry(item);
uow.UsageSessionWareHouseRepository.DbSet.Attach(item);
uow.UsageSessionWareHouseRepository.Context.Entry(item).State = EntityState.Modified;
}
else
{
uow.UsageSessionWareHouseRepository.DbSet.Add(item);
}
}
session.SessionStatus = "Processed";
var entry = uow.SessionWareHouseRepository.Context.Entry(session);
uow.SessionWareHouseRepository.DbSet.Attach(session);
entry.State = EntityState.Modified;
uow.Save();
}
在第一个循环中一切都很好,但在接下来我得到一个错误:
附加类型为“DataRetention.Core.DataEntities.WareHouseEntites.UsageSessionWareHouse”的实体失败,因为同一类型的另一个实体已经具有相同的主键值。如果图中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。这可能是因为某些实体是新实体,尚未收到数据库生成的键值。在这种情况下,使用“添加”方法或“已添加”实体状态来跟踪图形,然后将非新实体的状态设置为“未更改”或“已修改”。
我不知道如何像 DbSet.Add(item) 那样更新。
【问题讨论】:
标签: c# entity-framework transactions updates