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;
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: