What happened to AddOrUpdate in EF 7 / Core?

后端 未结 11 1275
暖寄归人
暖寄归人 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 09:51

    You can use this extension method I created to patch our codebase for the migration to EF Core:

       public static void AddOrUpdate(this DbSet dbSet, T data) where T : class
            {
                var t = typeof(T);
                PropertyInfo keyField = null;
                foreach (var propt in t.GetProperties())
                {
                    var keyAttr = propt.GetCustomAttribute();
                    if (keyAttr != null)
                    {
                        keyField = propt;
                        break; // assume no composite keys
                    }
                }
                if (keyField == null)
                {
                    throw new Exception($"{t.FullName} does not have a KeyAttribute field. Unable to exec AddOrUpdate call.");
                }
                var keyVal = keyField.GetValue(data);
                var dbVal = dbSet.Find(keyVal);
                if (dbVal != null)
                {
                    dbSet.Update(data);
                    return;
                }
                dbSet.Add(data);
            }
    

提交回复
热议问题