I have an issue where inside a class I want to update or add a row depending on the record existing inside the DB. In that, rather than having “Create/Update” methods I have a “Save(entity)” method.
The idea is the entity is checked against the database, if it exists then it’s an update if it doesn’t then its obviously a create.
Using EF 4.1 the problem is that once I read the row from the database via the same context, then this in turn creates a memory cache of that row. When I then try and replace the row via say an attach/add routine it will obviously throw an exception around the row already existing etc (as its trying to force both currentRow and newRow into the same table and fails in reconcillation).
My work-around for this is basically to use the .Remove() on the context which in marks the row for removal from memory and then re-add it in the same USING transaction.
var ctx = new SecurityContext(this.ConnectionString);
using(ctx)
{
var dbEntry = (ctx.Accounts.Where(a => a.AccountId == entity.AccountId || a.Username == entity.Username)).FirstOrDefault();
ctx.Accounts.Remove(dbEntry);
if (dbEntry != null)
{
ctx.Entry(entity).State = EntityState.Added;
} else
{
ctx.Accounts.Add(entity);
ctx.Entry(entity).State = EntityState.Added;
}
ctx.SaveChanges();
}
My Question is – is this the typical route to take? or is there much smarter / cleaner ways?
I believe this code should work, using
Attachrather thanAdd:Forgive the weird wrapping – wanted to make it fit on the page without scrolling.