[英]EF InsertOrUpdate with string PK
如果我有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;
这是因为执行“查找”时,它将返回对象并将副本保留在缓存中。 然后,您要添加一个新副本,因此有两个。
而是,您执行以下两项操作之一。 您可以修改查找结果返回的副本,如果可以假设CurrencyCode == null表示该副本在数据库中不存在,则只需添加或附加它。
因此,类似:
var currency = GetByCurrency(entity.CurrencyCode);
if (currency == null)
this.dbset.Add(entity);
else
currency.Something = entity.Something;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.