Skip to content

Commit

Permalink
Changed PrimaryKeyExpression to be object based instead of string based
Browse files Browse the repository at this point in the history
  • Loading branch information
Henk Kin committed Apr 2, 2020
1 parent 4891e2b commit 497a30b
Showing 1 changed file with 4 additions and 21 deletions.
25 changes: 4 additions & 21 deletions EntityCloner.Microsoft.EntityFrameworkCore/DbContextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,14 @@ private static Expression<Func<TEntity, bool>> CreatePrimaryKeyExpression<TEntit
$"CloneAsync only can handle id of type '{primaryKeyProperty.PropertyType.FullName}', passed id of type '{idPart?.GetType().FullName}'");
}

var idPartPredicate = BuildPredicate<TEntity>(primaryKeyProperty.Name, ExpressionType.Equal, idPart.ToString());
var idPartPredicate = BuildPredicate<TEntity>(primaryKeyProperty.Name, ExpressionType.Equal, idPart);
primaryKeyExpression = AndAlso(primaryKeyExpression, idPartPredicate);
}

return primaryKeyExpression;
}

private static Expression<Func<T, bool>> BuildPredicate<T>(string propertyName, ExpressionType comparison, string value)
private static Expression<Func<T, bool>> BuildPredicate<T>(string propertyName, ExpressionType comparison, object value)
{
var parameter = Expression.Parameter(typeof(T), "x");
var left = propertyName.Split('.').Aggregate((Expression)parameter, Expression.Property);
Expand All @@ -93,26 +93,9 @@ private static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool
Expression.Invoke(expr2, param)), param);
}

private static Expression MakeBinary(ExpressionType type, Expression left, string value)
private static Expression MakeBinary(ExpressionType type, Expression left, object value)
{
object typedValue = value;
if (left.Type != typeof(string))
{
if (string.IsNullOrEmpty(value))
{
typedValue = null;
if (Nullable.GetUnderlyingType(left.Type) == null)
left = Expression.Convert(left, typeof(Nullable<>).MakeGenericType(left.Type));
}
else
{
var valueType = Nullable.GetUnderlyingType(left.Type) ?? left.Type;
typedValue = valueType.IsEnum ? Enum.Parse(valueType, value) :
valueType == typeof(Guid) ? Guid.Parse(value) :
Convert.ChangeType(value, valueType);
}
}
var right = Expression.Constant(typedValue, left.Type);
var right = Expression.Constant(value, left.Type);
return Expression.MakeBinary(type, left, right);
}

Expand Down

0 comments on commit 497a30b

Please sign in to comment.