I\'m writing a seed method using EntityFramework.Core 7.0.0-rc1-final.
What happened to the AddOrUpdate method of DbSet?
I don't understand why people are trying to find the primary key in the other answers. Just pass it when you're calling the method as it's done in EF 6 AddOrUpdate method.
public static TEntity AddOrUpdate(this DbSet dbSet, DbContext context, Func identifier, TEntity entity) where TEntity : class
{
TEntity result = dbSet.Find(identifier.Invoke(entity));
if (result != null)
{
context.Entry(result).CurrentValues.SetValues(entity);
dbSet.Update(result);
return result;
}
else
{
dbSet.Add(entity);
return entity;
}
}
and use it later like this:
dbContext.MyModels.AddOrUpdate(dbContext, model => m.Id, new MyModel() { Id = 3 });
Clean and performant.