Say I have an insert method:
public T Add(T t)
{
context.Set().Add(t);
context.SaveChanges();
return t;
}
And a
You could use an interface and do something like this. I used an explicit implementation so the rest of your code does not have to deal with it.
// I am not 100% sold on my chosen name for the interface, if you like this idea change it to something more suitable
public interface IIsPersisted {
bool IsPersistedEntity{get;}
int Key {get;}
}
public class SomeEntityModel : IIsPersisted{
public int SomeEntityModelId {get;set;}
/*some other properties*/
bool IIsPersisted.IsPersistedEntity{get { return this.SomeEntityModelId > 0;}}
int IIsPersisted.Key {get{return this.SomeEntityModelId;}}
}
public T UpdateOrCreate(T updated) where T : class, IIsPersisted
{
if (updated == null)
return null;
if(updated.IsPersistedEntity)
{
T existing = _context.Set().Find(updated.Key);
if (existing != null)
{
context.Entry(existing).CurrentValues.SetValues(updated);
context.SaveChanges();
}
return existing;
}
else
{
context.Set().Add(updated);
context.SaveChanges();
return updated;
}
}
I just now saw this:
is there a more efficient way that avoids a round trip to the database than using
context.Set().Find(key)
If you want the whole entity updated from a detached state then the easiest thing to do is this.
context.Entry(updated).State = EntityState.Modified;
context.SaveChanges();
This will mark the whole entity as dirty and save everything back to the database.