What happened to AddOrUpdate in EF 7 / Core?

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

    This solution is, I think, a simpler solution to this problem, if assuming a base entity class is a legit option. The simplicity comes from your domain entities implementing DomainEntityBase, which alleviates a lot of the complexities in the other suggested solutions.

    public static class DbContextExtensions
    {
        public static void AddOrUpdate(this DbSet dbSet, IEnumerable records) 
            where T : DomainEntityBase
        {
            foreach (var data in records)
            {
                var exists = dbSet.AsNoTracking().Any(x => x.Id == data.Id);
                if (exists)
                {
                    dbSet.Update(data);
                    continue;
                }
                dbSet.Add(data);
            }
        }
    }
    
    public class DomainEntityBase
    {
        [Key]
        public Guid Id { get; set; }
    }
    

提交回复
热议问题