LINQ to Entities only supports casting EDM primitive or enumeration types with IEntity interface
I was able to resolve this by adding the class
generic type constraint to the extension method. I'm not sure why it works, though.
public static T GetById<T>(this IQueryable<T> collection, Guid id)
where T : class, IEntity
{
//...
}
Some additional explanations regarding the class
"fix".
This answer shows two different expressions, one with and the other without where T: class
constraint. Without the class
constraint we have:
e => e.Id == id // becomes: Convert(e).Id == id
and with the constraint:
e => e.Id == id // becomes: e.Id == id
These two expressions are treated differently by the entity framework. Looking at the EF 6 sources, one can find that the exception comes from here, see ValidateAndAdjustCastTypes()
.
What happens is, that EF tries to cast IEntity
into something that makes sense the domain model world, however it fails in doing so, hence the exception is thrown.
The expression with the class
constraint does not contain the Convert()
operator, cast is not tried and everything is fine.
It still remain open question, why LINQ builds different expressions? I hope that some C# wizard will be able to explain this.
Entity Framework doesn't support this out of the box, but an ExpressionVisitor
that translates the expression is easily written:
private sealed class EntityCastRemoverVisitor : ExpressionVisitor
{
public static Expression<Func<T, bool>> Convert<T>(
Expression<Func<T, bool>> predicate)
{
var visitor = new EntityCastRemoverVisitor();
var visitedExpression = visitor.Visit(predicate);
return (Expression<Func<T, bool>>)visitedExpression;
}
protected override Expression VisitUnary(UnaryExpression node)
{
if (node.NodeType == ExpressionType.Convert && node.Type == typeof(IEntity))
{
return node.Operand;
}
return base.VisitUnary(node);
}
}
The only thing you'll have to to is to convert the passed in predicate using the expression visitor as follows:
public static T GetById<T>(this IQueryable<T> collection,
Expression<Func<T, bool>> predicate, Guid id)
where T : IEntity
{
T entity;
// Add this line!
predicate = EntityCastRemoverVisitor.Convert(predicate);
try
{
entity = collection.SingleOrDefault(predicate);
}
...
}
Another -less flexible- approach is to make use of DbSet<T>.Find
:
// NOTE: This is an extension method on DbSet<T> instead of IQueryable<T>
public static T GetById<T>(this DbSet<T> collection, Guid id)
where T : class, IEntity
{
T entity;
// Allow reporting more descriptive error messages.
try
{
entity = collection.Find(id);
}
...
}