What happened to AddOrUpdate in EF 7 / Core?

后端 未结 11 1268
暖寄归人
暖寄归人 2020-12-16 09:30

I\'m writing a seed method using EntityFramework.Core 7.0.0-rc1-final.

What happened to the AddOrUpdate method of DbSet?

11条回答
  •  暖寄归人
    2020-12-16 10:03

    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.

提交回复
热议问题