DEV Community

Alex
Alex

Posted on

Entity Framework Core Add if not exist

Have you tried to check if the entity exists and if not — add it.

you can use this code

using Microsoft.EntityFrameworkCore.ChangeTracking;
public static class DbSetExtensions
{
public static EntityEntry<T> AddIfNotExists<T>(this DbSet<T> dbSet, T entity, Expression<Func<T, bool>> predicate = null) where T : class, new()
{
var exists = predicate != null ? dbSet.Any(predicate) : dbSet.Any();
return !exists ? dbSet.Add(entity) : null;
}
}
Enter fullscreen mode Exit fullscreen mode

and

var purchase = new Models.Purchase();
var trackingnumber= "222";
_context.Purchases.AddIfNotExists(purchase,p=>p.BankTrackingNum== trackingnumber);
await _context.SaveChangesAsync();
Enter fullscreen mode Exit fullscreen mode

“Read before write” can violate data integrity without being put inside a transaction control.

In SQL Server, you can use merge statement. However merge statement is not available in EF.

Happy Coding👨‍💻

Top comments (0)