带字符串 PK 的 EF InsertOrUpdate
如果我有CurrencyId,我会做这样的事情:
public void InsertOrUpdate(Currency entity)
{
if (entity.CurrencyId == default(int))
{
// New entity
this.dbset.Add(entity);
}
else
{
// Existing entity
this.context.Entry(entity).State = EntityState.Modified;
}
}
但我使用字符串CurrencyCode作为PK,并且我希望能够添加或编辑它。所以我必须检查数据库中是否存在CurrencyCode。我该怎么做?
添加新实体是可以的,但如果我尝试编辑:
public void InsertOrUpdate(Currency entity)
{
if (GetByCurrency(entity.CurrencyCode) == null)
{
// New entity
this.dbset.Add(entity);
}
else
{
// Existing entity
this.context.Entry(entity).State = EntityState.Modified;
}
}
public Currency GetByCurrency(string currencyCode)
{
return this.dbset.Find(currencyCode);
}
我得到
ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同属性的多个对象 关键。
在
this.context.Entry(entity).State = EntityState.Modified;
If I had CurrencyId, I would do something like this:
public void InsertOrUpdate(Currency entity)
{
if (entity.CurrencyId == default(int))
{
// New entity
this.dbset.Add(entity);
}
else
{
// Existing entity
this.context.Entry(entity).State = EntityState.Modified;
}
}
But I'm using a string CurrencyCode as a PK and I'd like to be able to Add or Edit it. So I have to check whether the CurrencyCode exists in the db or not. How do I do this?
Adding a new entity is ok, but if I try to Edit:
public void InsertOrUpdate(Currency entity)
{
if (GetByCurrency(entity.CurrencyCode) == null)
{
// New entity
this.dbset.Add(entity);
}
else
{
// Existing entity
this.context.Entry(entity).State = EntityState.Modified;
}
}
public Currency GetByCurrency(string currencyCode)
{
return this.dbset.Find(currencyCode);
}
I'm getting
An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same
key.
in
this.context.Entry(entity).State = EntityState.Modified;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为当您执行查找时,它会返回对象并在缓存中保留一个副本。然后您将添加一个新副本,因此有两个。
相反,您要做两件事之一。您可以修改查找返回的副本,如果您可以假设CurrencyCode == null意味着它不存在于数据库中,那么只需添加它或附加它。
所以,像这样:
That's because when you do the Find, it's returning the object and keeping a copy in the cache. You are then adding a new copy, so there are two.
Instead, you do one of two things. You either modify the copy returned by the find, if you can assume that CurrencyCode == null means it doesn't exist in the database, then just add it or attach it.
So, something like: