Last active
October 27, 2015 10:40
-
-
Save MrAntix/ddf11b9f0900ada3d3b8 to your computer and use it in GitHub Desktop.
AddOnce Seed extension for EF 6 using LinqKit
This file contains hidden or 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 Extensions | |
{ | |
public static void AddOnce<TEntity>( | |
this IDbSet<TEntity> set, | |
Expression<Func<TEntity, object>> identifierExpression, | |
params TEntity[] entities) where TEntity : class | |
{ | |
if (set == null) throw new ArgumentNullException("set"); | |
if (identifierExpression == null) throw new ArgumentNullException("identifierExpression"); | |
if (entities == null) throw new ArgumentNullException("entities"); | |
var query = set.AsExpandable(); | |
var getIdentifier = identifierExpression.Compile(); | |
foreach (var entity in entities) | |
{ | |
var entityIdentifier = getIdentifier(entity); | |
if (!query | |
.Any(i => identifierExpression.Invoke(i) == entityIdentifier)) | |
{ | |
set.Add(entity); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment