Musings on code and life

Entity Framework Migrations AddIfNotExist

I normally use the Entity Framework Migrations IDbSet extension method AddOrUpdate, however I had a need to only add a record if it didn't exist so I created this simple AddIfNotExist extension method.


public static void AddIfNotExist<TEntity>(this IDbSet<TEntity> set, Expression<Func<TEntity, object>> identifierExpression, params TEntity[] entities) where TEntity : class
{
    var pi = GetPropertyFromExpression(identifierExpression);
    var parameter = Expression.Parameter(typeof(TEntity));
    foreach (var entity in entities)
    {
        var id = pi.GetValue(entity, null);
        var body = Expression.Equal(Expression.Property(parameter, pi), Expression.Constant(id));
        var found = set.SingleOrDefault(Expression.Lambda<Func<TEntity, bool>>(body, new[] { parameter }));
        if (found == null)
        {
            set.Add(entity);
        }
    }
}