Entity Framework does not support this out of the box, but ExpressionVisitor , which 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 need to do is convert the visitor passed into the predicate using the expression as follows:
public static T GetById<T>(this IQueryable<T> collection, Expression<Func<T, bool>> predicate, Guid id) where T : IEntity { T entity;
Another flexible approach is to use 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); } ... }
Steven Sep 24 '13 at 8:27 2013-09-24 08:27
source share