Add upsert methods to EF. Not optimized implementation.

This commit is contained in:
ngfrolov 2022-06-10 17:30:42 +05:00
parent 12c97a4119
commit 04b085b2ec

View File

@ -49,6 +49,32 @@ namespace AsbCloudDb
var factory = GetQueryStringFactory(dbSet);
return factory.Columns;
}
public static Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<T> Upsert<T>(this DbSet<T> dbSet, T value)
where T : class
{
return dbSet.Contains(value)
? dbSet.Update(value)
: dbSet.Add(value);
}
public static (int updated, int inserted) UpsertRange<T>(this DbSet<T> dbSet, IEnumerable<T> values)
where T : class
{
(int updated, int inserted) stat = (0,0);
foreach (var value in values)
if (dbSet.Contains(value))
{
stat.updated++;
dbSet.Update(value);
}
else
{
stat.inserted++;
dbSet.Add(value);
}
return stat;
}
}
interface IQueryStringFactory { }