I\'m writing a seed method using EntityFramework.Core 7.0.0-rc1-final.
What happened to the AddOrUpdate method of DbSet?
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; }
}