I'm using EntityFramework and LinqKit to build expressions trees which get translated into SQL. Also we use the specification pattern to organize our queries.
There is a need in almost all of our domain objects to execute a query by description, but in some of those classes the property is called "Name", in others "Description", etc.
So initially was defined a interface as follow:
public interface IDescritible
{
string Description { get; }
}
The problem appeared when I tried to use it implemented explicitly in a class and made a generic query upon that:
public class Foo : IDescritible
{
public string Name { get; set; }
string IDescritible.Description
{
get { return this.Name; }
}
}
public class DescriptionMatch<T> : AbstractSpecification<T>
where T : IDescritible
{
public string Query { get; set; }
public DescriptionMatch(string query)
{
this.Query = query;
}
public override Expression<Func<T, bool>> IsSatisfiedBy()
{
return x => x.Description.Contains(Query);
}
}
When run, the EntityFramework is unable to translate the property get (a method call) into a SQL expression.
Then I tried to define a Expression in the class as follows:
public interface IDescritible<T> where T: IDescritible<T>
{
Expression<Func<T, string>> DescriptionExpression { get; }
}
public class Foo : IDescritible<Foo>
{
public string Name { get; set; }
public Expression<Func<Foo, string>> DescriptionExpression
{
get { return x => x.Name; }
}
}
public class DescriptionMatch<T> : AbstractSpecification<T> where T : IDescritible<T>
{
public string Query { get; set; }
public DescriptionMatch(string query)
{
this.Query = query;
}
public override Expression<Func<T, bool>> IsSatisfiedBy()
{
Expression<Func<T, bool>> combinedExpression = x => x.DescriptionExpression.Invoke(x).Contains(this.Query);
return combinedExpression.Expand();
}
}
But when it executes the .Expand() a exception is thrown: Unable to cast object of type 'System.Linq.Expressions.PropertyExpression' to type 'System.Linq.Expressions.LambdaExpression'.
Then I found out that LinqKit only support expanding local defined expressions (as stated on this question) and that there are some unoficial code write to solve those issues (answers on this question).
But when I modified the LinqKit library to try either one of the proposed solutions in second question it started to throw: variable 'x' of type 'Foo' referenced from scope '', but it is not defined.
Maybe that was caused by the fact that I don't have a instance of Foo yet? Only got the generic type parameter, and that's why I can't define my expression on a local variable. Maybe there is a way to define as a static expression somehow "attached" into class? But then I would not be able to use it in a generic query, there will be no interface...
There is a way to modify LinqKit so I can build expressions defined on a explicit implementation of a interface? Or there is another way to make a generic query upon properties explicitly implemented? Or any other solution or things to look into?
There is no need to use neither LinqKit or specification pattern for that, but EntityFramework is mandatory, what is important is to have a interface/any other way that support "pointing out" which property is the description property and make a generic Expression upon that.
Thank you in advance!
The easiest way to do it is to make the following change
public class DescriptionMatch<T> : AbstractSpecification<T> where T : IDescritible<T>, new()
Then you can get an instance by simply newing up a T (which EF), using the expression and otherwise discarding the object
public interface IDescritible<T> where T : IDescritible<T>
{
Expression<Func<T, string>> DescriptionExpression { get; }
}
public class Foo : IDescritible<Foo>
{
public string Name { get; set; }
public Expression<Func<Foo, string>> DescriptionExpression
{
get { return x => x.Name; }
}
}
public abstract class AbstractSpecification<T>
{
public abstract Expression<Func<T, bool>> IsSatisfiedBy();
}
public class DescriptionMatch<T> : AbstractSpecification<T>
where T : IDescritible<T>, new()
{
public string Query { get; set; }
public DescriptionMatch(string query)
{
this.Query = query;
}
public override Expression<Func<T, bool>> IsSatisfiedBy()
{
Expression<Func<T, string>> lambda = new T().DescriptionExpression;
return Expression.Lambda<Func<T, bool>>(
Expression.Call(
lambda.Body,
"Contains",
Type.EmptyTypes,
Expression.Constant(
this.Query,
typeof(string)
)
),
lambda.Parameters
);
}
}
public class ExpressionReplacer : ExpressionVisitor
{
private readonly Expression _toBeReplaced;
private readonly Expression _replacement;
public ExpressionReplacer(Expression toBeReplaced, Expression replacement)
{
if (toBeReplaced.Type != replacement.Type)
{
throw new ArgumentException();
}
this._toBeReplaced = toBeReplaced;
this._replacement = replacement;
}
public override Expression Visit(Expression node)
{
return Object.ReferenceEquals(node, this._toBeReplaced) ? this._replacement : base.Visit(node);
}
}
Related
I'm trying to implement class that defines filter, to make it more explicit when it will be passed as argument to methods in my repository class (EF).
And I have a problem with definition of implicit operator from Expression to my class.
Is it possible to make implementation for syntax near fd4 variable?
public class FilterDefinition<TEntity>
where TEntity : class
{
public FilterDefinition() { }
public FilterDefinition(Expression<Func<TEntity, bool>> filter)
{
this.Filter = filter;
}
public virtual Expression<Func<TEntity, bool>> Filter { get; set; }
public static implicit operator FilterDefinition<TEntity>(Expression<Func<TEntity, bool>> filter) => new FilterDefinition<TEntity>(filter);
}
public class SomeEntity
{
public bool SomeBool { get; set; }
}
class Program
{
static void Main()
{
FilterDefinition<SomeEntity> fd1 = new FilterDefinition<SomeEntity>(x => x.SomeBool);
FilterDefinition<SomeEntity> fd2 = new FilterDefinition<SomeEntity> { Filter = x => x.SomeBool };
FilterDefinition<SomeEntity> fd3 = (Expression<Func<SomeEntity, bool>>)(x => x.SomeBool);
//FilterDefinition<SomeEntity> fd4 = x => x.SomeBool;
Console.ReadKey();
}
}
The purpose of FilterDefinition class was to pass as argument to generic repository of queries. And using inheritance define commonly used filters.
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : class
{
private readonly DbSet<TEntity> dbSet;
public Repository(DbContext context)
{
this.dbSet = context.Set<TEntity>();
}
public async Task<IEnumerable<TEntity>> GetAsync(
FilterDefinition<TEntity> filter = null,
OrderDefinition<TEntity> order = null,
PagingDefinition paging = null)
{
return await new QueryBuilder<TEntity>(this.dbSet)
.ApplyFilter(filter)
.ApplyOrder(order)
.ApplyPaging(paging)
.ToQuery()
.ToListAsync();
}
The short answer would be "not in this scenario", because syntactically, in fd4 you're not actually casting from an Expression[...] to your type. The compiler doesn't know that the lambda represents an Expression[...] until it knows what it is trying to do with the value; a lambda (x => x.SomeBool) can be interpreted as a wide range of both expression-tree types and delegate types (for anonymous methods), and the compiler here would not understand that you mean "treat the lambda as an Expression<Func<SomeEntity, bool>>, then use the implicit conversion operator to change the expression to a FilterDefinition". It simply can't (and doesn't) make that leap. You can get close, as with your fd3 example, but... a large part of me is wondering what FilterDefinition actually does here, because to an outside observer it doesn't really seem to add anything over the raw expression tree.
I have a problem regarding generic expressions.
I have an Expression<Func<T, bool>> and I want to convert the Expression<Func<T, bool>> to Expression<Func<Y, bool>>. The object of class T has the same properties as the class Y.
Does anybody know how to solve this?
The "preferred" way to do this is use a Interface that contains the property you care about.
interface IMyProp
{
string SomeProp {get;}
}
class T : IMyProp
{
public string SomeProp
{
get
{
//Some complicated logic
}
}
}
class Y : IMyProp
{
public string SomeProp {get; set;}
}
The just code your expression to Expression<Func<IMyProp, bool>>
However it is understandable that you can not always do this, for situations like this you can use a library like AutoMapper
class T
{
public string SomeProp
{
get
{
//Some complicated logic
}
}
}
class Y
{
public string SomeProp {get; set;}
}
//Some initiation code somewhere else in your project
public static void InitializeMappings()
{
Mapper.CreateMap<T, Y>();
}
public static IQueryable<Y> FilterOnTAndMapToY(IQueryable<T> source, Expression<Func<T,bool>> filter)
{
return source.Where(filter).Project().To<Y>();
}
Now this does not exactly turn your Expression<Func<T, bool>> in to a to Expression<Func<Y, bool>> but it does let you use your T expression and use it to get a Y result after the filtering has been applied.
The way AutoMapper's Queryable Extensions work is the querys and casts to go from T to Y happen all server side when you are doing LinqToEntities. So you could even do
public static IQueryable<Y> MultiFilterCast(IQueryable<T> source, Expression<Func<T,bool>> tTypeFilter, Expression<Func<Y,bool>> yTypeFilter)
{
var filteredStage1 = source.Where(tTypeFilter);
var castToY = filteredStage1.Project().To<Y>();
var filteredStage2 = castToY.Where(yTypeFilter);
return filteredStage2;
}
both tTypeFilter and yTypeFilter will be applied server side before you get the result set.
The goal is to do something like this using NHibernate and Linq:
Session.Query<MyClass>().Where(x => x.DateGreaterThen(DateTime.Now))
This example is a little bit simplified, but the idea is that in Where predicate I would like to call MyClass method. So MyClass looks like:
public class MyClass
{
public static readonly Expression<Func<MyClass, DateTime, bool>> GreaterThenExpression =
(x, dt) => x.MyDateTimeProperty > dt.Date;
private static readonly Func<MyClass, DateTime, bool> GreaterThenFunc = GreaterThenExpression.Compile();
public Guid Id { get; set; }
public DateTime MyDateTimeProperty { get; set; }
public bool DateGreaterThen(DateTime dt)
{
return GreaterThenFunc(this, dt);
}
}
Custom generator:
public class EntityMethodGenerator<T1, T2, TResult> : BaseHqlGeneratorForMethod
{
private Expression<Func<T1, T2, TResult>> _returnValueExpression;
public EntityMethodGenerator()
{
SupportedMethods = new[]
{
ReflectionHelper.GetMethodDefinition<MyClass>(myClass => myClass.DateGreaterThen(DateTime.Now))
};
}
public static void Register(ILinqToHqlGeneratorsRegistry registry, Expression<Action<T1>> method, Expression<Func<T1, T2, TResult>> returnValueExpression)
{
var generator = new EntityMethodGenerator<T1, T2, TResult> { _returnValueExpression = returnValueExpression };
registry.RegisterGenerator(ReflectionHelper.GetMethodDefinition(method), generator);
}
public override HqlTreeNode BuildHql(
MethodInfo method,
Expression targetObject,
ReadOnlyCollection<Expression> arguments,
HqlTreeBuilder treeBuilder,
IHqlExpressionVisitor visitor)
{
return visitor.Visit(_returnValueExpression);
}
}
And finally custom custom generators registry:
public class OwnLinqToHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
{
public OwnLinqToHqlGeneratorsRegistry()
{
EntityMethodGenerator<MyClass, DateTime, bool>.Register(this, (myClass) => myClass.DateGreaterThen(DateTime.Now), MyClass.GreaterThenExpression);
}
}
But this is not working, I am getting System.Data.SqlClient.SqlException : Invalid column name 'dt'. I am suspecting that my BuildHql method is not implemented correctly, any help with fixing this?
By the way, I would like to use expressions in generator, like my GreaterThenExpression rather than building HqlTree manually in BuildHql method
GreaterThenExpression is a lamba. In BuildHql() you need to also take notice of the targetObject and the arguments, otherwise you are just inserting some HQL conversion of the unapplied lambda in the HQL tree.
You need to extract the body of the lambda and replace its parameters with the targetObject and arguments. Then you can generate HQL from that. Try using Remotion.Linq.Parsing.ExpressionTreeVisitors.MultiReplacingExpressionTreeVisitor.
(On a side note, it should be GreaterThan, not GreaterThen.)
I've started using C# Expression constructs, and I've got a question about how generics are applied in the following situation:
Consider I have a type MyObject which is a base class for many different types. Inside this class I have the following code:
// This is a String Indexer Expression, used to define the string indexer when the object is in a collection of MyObjects
public Expression<Func<MyObject, string, bool>> StringIndexExpression { get; private set;}
// I use this method in Set StringIndexExpression and T is a subtype of MyObject
protected void DefineStringIndexer<T>(Expression<T, string, bool>> expresson) where T : MyObject
{
StringIndexExpression = expression;
}
This is how I use DefineStringIndexer:
public class MyBusinessObject : MyObject
{
public string Name { get; set; }
public MyBusinessObject()
{
Name = "Test";
DefineStringIndexer<MyBusinessObject>((item, value) => item.Name == value);
}
}
However in the assignment inside DefineStringIndexer I get the compile error:
Cannot implicitly convert type
System.Linq.Expression.Expression< MyObject, string, bool > to
System.Linq.Expression.Expression < MyBusinessObject, string, bool >>
Can I use Generics with C# Expressions in this situation? I want to use T in DefineStringIndexer so I can avoid casting MyObject inside the lambda.
The assignment will not work, because the Func<MyBusinessObject,string,bool> type is not assignment-compatible with Func<MyObject,string,bool>. However, the parameters of the two functors are compatible, so you can add a wrapper to make it work:
protected void DefineStringIndexer<T>(Func<T,string,bool> expresson) where T : MyObject {
StringIndexExpression = (t,s) => expression(t, s);
}
Would this work better for you?
Edit: Added <T> to constraint - think you will need that :)
class MyObject<T>
{
// This is a String Indexer Expression, used to define the string indexer when the object is in a collection of MyObjects
public Expression<Func<T, string, bool>> StringIndexExpression { get; private set;}
// I use this method in Set StringIndexExpression and T is a subtype of MyObject
protected void DefineStringIndexer<T>(Expression<T, string, bool>> expresson)
where T : MyObject<T> // Think you need this constraint to also have the generic param
{
StringIndexExpression = expression;
}
}
then:
public class MyBusinessObject : MyObject<MyBusinessObject>
{
public string Name { get; set; }
public MyBusinessObject()
{
Name = "Test";
DefineStringIndexer<MyBusinessObject>((item, value) => item.Name == value);
}
}
I'm trying to convert this:
ISession.Query<Question>()
.Where(x => x.QuestionId == q.QuestionId)
.FetchMany(x => x.Answers)
.ToFuture();
To reflection type:
IQueryable<Question> query = ISession.Query<Question>().Where(string.Format("{0} = #0", "QuestionId"), q.QuestionId);
Type emType = typeof(NHibernate.Linq.EagerFetchingExtensionMethods);
MethodInfo mi = emType.GetMethod("FetchMany");
ParameterExpression paramEx = Expression.Parameter(typeof(Question), "x");
MemberExpression me = Expression.Property(paramEx, "Answers");
LambdaExpression lambdaEx = Expression.Lambda (me, paramEx);
// runtime error here
mi.MakeGenericMethod(typeof(Question), typeof(Answer)).Invoke(emType, new object[] { query, lambdaEx });
The runtime error:
System.ArgumentException: Object of type
'System.Linq.Expressions.Expression`1
[System.Func`2[TestXXX.TheModels.Question,
System.Collections.Generic.IList`1[TestXXX.TheModels.Answer]]]'
cannot be converted to type
'System.Linq.Expressions.Expression`1
[System.Func`2[TestXXX.TheModels.Question,
System.Collections.Generic.IEnumerable`1[TestXXX.TheModels.Answer]]]'.
POCO sample:
The Answers in Question is an IList, please don't advise to change IList to IEnumerable ;-)
public class Question
{
public virtual int QuestionId { get; set; }
public virtual string QuestionText { get; set; }
public virtual IList<Answer> Answers { get; set; }
}
Here's the method signature of FetchMany:
namespace NHibernate.Linq
{
public static class EagerFetchingExtensionMethods
{
public static INhFetchRequest<TOriginating, TRelated> Fetch<TOriginating, TRelated>(this IQueryable<TOriginating> query, Expression<Func<TOriginating, TRelated>> relatedObjectSelector);
public static INhFetchRequest<TOriginating, TRelated> FetchMany<TOriginating, TRelated>(this IQueryable<TOriginating> query, Expression<Func<TOriginating, IEnumerable<TRelated>>> relatedObjectSelector);
public static INhFetchRequest<TQueried, TRelated> ThenFetch<TQueried, TFetch, TRelated>(this INhFetchRequest<TQueried, TFetch> query, Expression<Func<TFetch, TRelated>> relatedObjectSelector);
public static INhFetchRequest<TQueried, TRelated> ThenFetchMany<TQueried, TFetch, TRelated>(this INhFetchRequest<TQueried, TFetch> query, Expression<Func<TFetch, IEnumerable<TRelated>>> relatedObjectSelector);
}
}
What should be done so it's possible to pass an IList to NHibernate's FetchMany's IEnumerable during reflection?
Note: can pass IList to IEnumerable if we are not using reflection
Change this
MemberExpression me = Expression.Property(paramEx, "Answers");
to this:
Expression me = Expression.Convert(Expression.Property(paramEx, "Answers"), typeof(IEnumerable<Answer>));
The reason for the error you are receiving is that the delegate types of your lambda do not agree. We need to make the types compatible by artificially treating an IList<T> as an IEnumerable<T>.
This is kind of a hack as any proponent of dynamic languages would say ;-) Anyway, it reliably works.