Created
October 28, 2014 12:41
-
-
Save mtranter/f4c8ff9684730b764f5b to your computer and use it in GitHub Desktop.
AddIfNotExists DBSet Extension Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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