What happened to AddOrUpdate in EF 7 / Core?

后端 未结 11 1262
暖寄归人
暖寄归人 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

    I started with Tjaart's answer and modified two things:

    1. I'm using the fluent api for key designation so I'm looking for the entity's primary key instead of an attribute on the entity
    2. I have change tracking turned on and was getting the error others have mentioned regarding that EF is already tracking it. This does a find on the already tracked entity and copies the values from the incoming entity to it, then updates the original entity

      public TEntity AddOrUpdate(TEntity entity)
      {
          var entityEntry = Context.Entry(entity);
      
          var primaryKeyName = entityEntry.Context.Model.FindEntityType(typeof(TEntity)).FindPrimaryKey().Properties
              .Select(x => x.Name).Single();
      
          var primaryKeyField = entity.GetType().GetProperty(primaryKeyName);
      
          var t = typeof(TEntity);
          if (primaryKeyField == null)
          {
              throw new Exception($"{t.FullName} does not have a primary key specified. Unable to exec AddOrUpdate call.");
          }
          var keyVal = primaryKeyField.GetValue(entity);
          var dbVal = DbSet.Find(keyVal);
      
          if (dbVal != null)
          {
              Context.Entry(dbVal).CurrentValues.SetValues(entity);
              DbSet.Update(dbVal);
      
              entity = dbVal;
          }
          else
          {
              DbSet.Add(entity);
          }
      
          return entity;
      }
      

    I've been able to get decent mileage out of it so far without any problems.

    I'm using this on EFCore 2.1

提交回复
热议问题