Skip to content

Instantly share code, notes, and snippets.

@mtranter
Created October 28, 2014 12:41
Show Gist options
  • Save mtranter/f4c8ff9684730b764f5b to your computer and use it in GitHub Desktop.
Save mtranter/f4c8ff9684730b764f5b to your computer and use it in GitHub Desktop.
AddIfNotExists DBSet Extension Method
public static class DbSetExtensions
{
public static void AddIfNotExists<TEntity, TProperty>(this IDbSet<TEntity> dbSet,
Expression<Func<TEntity, TProperty>> selector,
params TEntity[] toAdd) where TEntity : class
{
var compiled = selector.Compile();
foreach (var entity in toAdd)
{
var key = compiled(entity);
var predicate = BuildPredicate(selector, key);
if (!dbSet.Any(predicate))
{
dbSet.Add(entity);
}
}
}
private static Expression<Func<TEntity, bool>> BuildPredicate<TEntity, TProperty>(
Expression<Func<TEntity, TProperty>> selector, TProperty comparer)
{
var body = selector.Body;
var newBody = Expression.Equal(body, Expression.Constant(comparer));
return Expression.Lambda<Func<TEntity, bool>>(newBody, selector.Parameters[0])'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment