DEV Community

Alex
Alex

Posted on

7 1

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)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay