【发布时间】:2017-07-14 01:03:59
【问题描述】:
我正在尝试让 upsert 与实体框架一起工作。我有以下引发错误的代码:
using (var db = new Entities.DB.DConn())
{
//...
foreach (Account account in accounts)
{
Entities.DB.Account dlAccount = new Entities.DB.Account();
dlAccount.GId = dlG.Id;
dlAccount.AccountName = account.NameAtFI;
dlAccount.AccountNumber = account.AcctNumber;
dlAccount.AcctType = account.AcctType;
dlAccount.AsOfDate = account.DateCreated;
dlAccount.IsDeleted = false;
dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime();
db.Entry(dlAccount).State = ((dlAccount.GId == dlG.Id) ? EntityState.Modified : EntityState.Added);
db.SaveChanges();
}
}
例外:
存储更新、插入或删除语句影响了意外数量的行 (0)。自加载实体后,实体可能已被修改或删除。
基本上我要做的就是更新记录if dlAccount.GId == dlG.Id,或者如果它不存在则插入它。以下代码在不使用 EntityState 的情况下实现了我想要的:
using (var db = new Entities.DB.DConn())
{
//...
foreach (Account account in accounts)
{
bool isNewRecord = false;
Entities.DB.Account dlAccount = new Entities.DB.Account();
Entities.DB.Account exisitngAcct = db.Accounts.Where(x => x.GId == dlG.Id).FirstOrDefault(); //x.GId is NOT ad primary key
if (exisitngAcct != null)
{
dlAccount = exisitngAcct;
isNewRecord = true;
}
dlAccount.GId = dlG.Id;
dlAccount.AccountName = account.NameAtFI;
dlAccount.AccountNumber = account.AcctNumber;
dlAccount.AcctType = account.AcctType;
dlAccount.AsOfDate = account.DateCreated;
dlAccount.IsDeleted = false;
dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime();
if (isNewRecord)
{
dldb.Accounts.Add(dlAccount);
}
db.SaveChanges();
}
}
谁能看到我在这里做错了什么?我真的很想让这个工作,避免使用像上面那样臃肿的代码。
TIA
【问题讨论】:
-
您在共享代码的开头附近将它们设置为彼此相等,因此它们具有相同的值,那么为什么还要麻烦检查呢? (
dlAccount.GId = dlG.Id;) -
您是否将实体添加到上下文中以便对其进行跟踪...?
-
@Igor 在插入的情况下需要设置这些值。我想我对如何评估记录是否存在感到困惑。
-
@JoePhillips 不,你所看到的就是我所拥有的。我错过了什么吗?
标签: c# entity-framework-6