Generating Expression<Func<T, object>> arguments - c#

I have a method like this:
public static MvcHtmlString Pager<T>(T urlParams, Expression<Func<T, object>> pageProperty) where T : class
{
string pagingProp = Helpers.PropertyToString(pageProperty.Body);
//set property on object using reflection.
PropertyInfo prop = type.GetProperty(urlParams.GetType());
}
The purpose of the expression is to know what property of urlParams is the one that should be used for paging.
Lets say I have the class:
public class Pagination
{
public int PageIndex {get; set; }
}
I would like to call it like this:
Html.Pager(new Pagination{ PageIndex = 1 }, new Expression<Func<Pagination>>(p => p.PageIndex))
Problem: Expression<Func<Pagination>>() does take a constructor, how do I tell the expression I want to use the PageIndex property?

Assuming:
void M(Expression<Func<User, object>> f) { /* ... some implementation ... */ }
Then:
M(u => u.Password);

Related

Query over interface properties using EntityFramework and LinqKit

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);
}
}

Creating generic Expression

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.

Extending linq-to-nhibernate with custom hql generator

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.)

Generic constraints with C# Expression<TDelegate> - Cannot implicitly convert Type

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);
}
}

Attribute and Functions in constructor

I want to do this:
[AttributeUsage(AttributeTargets.Property,
Inherited = false,
AllowMultiple = true)]
sealed class MyAttribute : Attribute
{
readonly string showName;
readonly Type controlType;
public Type ControlType
{
get { return controlType; }
}
readonly Func<Control, object> selector;
public Func<Control, object> Selector
{
get { return selector; }
}
public MyAttribute(string showName,
Type controlType,
Func<Control, object> selector)
{
this.showName = showName;
this.controlType = controlType;
this.selector = selector;
}
public string ShowName
{
get { return showName; }
}
}
class Foo
{
// problem. Do you have an idea?
[My("id number",
typeof(NumericUpDown),
Convert.ToInt32(control=>((NumericUpDown)control).Value))]
public int Id { get; set; }
}
I want to do attribute that contains name, type of control, and selector for take from the control the value of the property.
I try do it, and can't.
No, you cannot use an anonymous method or lambda expression in an attribute decoration.
Incidentally, if you could, it would be (moving the control declaration):
control=>Convert.ToInt32(((NumericUpDown)control).Value)
But... You can't. Either use the string name of a method that you resolve with reflection, or use something like a subclass of the attribute class with a virtual method override instead.
You cannot use lambda expressions in attribute declarations. I had this problem too and sloved it by using a dictionary with a string as key for the lambdas. In the attribute I then only declared the key given to the lambda.
Dictionary<string, Func<Control, object>> funcDict = new Dictionary<string, Func<Control, object>>();
funcDict.Add("return text", c => c.Text);
The attribute is used like this:
[MyAttribute("show", typeof(TextBox), "return text")]

Categories