Skip to content

Instantly share code, notes, and snippets.

@MrAntix
Last active October 27, 2015 10:40
Show Gist options
  • Save MrAntix/ddf11b9f0900ada3d3b8 to your computer and use it in GitHub Desktop.
Save MrAntix/ddf11b9f0900ada3d3b8 to your computer and use it in GitHub Desktop.
AddOnce Seed extension for EF 6 using LinqKit
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