Entity Framework Add if not exist without update

Have you tried to check if the entity exists and if not – add it? Like this :

UPDATE

using System.Linq.Expressions;

public class ContextWithExtensionExample
{
    public void DoSomeContextWork(DbContext context)
    {
        var uni = new Unicorn();
        context.Set<Unicorn>().AddIfNotExists(uni, x => x.Name == "James");
    }
}

public static class DbSetExtensions
{
    public static 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;
    }
}

You can use this method directly and remember to call DbContext.SaveChanges() after the call.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)