I am trying to build a lambda expression, containing two assignments (as shown further down), that I can then pass to a Queryable.Select() method.
I am trying to pass a string variable into a method and then use that variable to build up the lambda expression so that I can use it in a LINQ Select query.
My reasoning behind it is that I have a SQL Server datasource with many column names, I am creating a charting application that will allow the user to select, say by typing in the column name, the actual column of data they want to view in the y-axis of my chart, with the x-axis always being the DateTime. Therefore, they can essentially choose what data they chart against the DateTime value (it’s a data warehouse type app).
I have, for example, a class to store the retrieved data in, and hence use as the chart source of:
public class AnalysisChartSource
{
public DateTime Invoicedate { get; set; }
public Decimal yValue { get; set; }
}
I have (purely experimentaly) built an expression tree for the Where clause using the String value and that works fine:
public void GetData(String yAxis)
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
var data = this.FunctionOne().AsQueryable<AnalysisChartSource>();
//just to get some temp data in....
ParameterExpression pe = Expression.Parameter(typeof(AnalysisChartSource), "p");
Expression left = Expression.MakeMemberAccess(pe,
typeof(AnalysisChartSource).GetProperty(yAxis));
Expression right = Expression.Constant((Decimal)16);
Expression e2 = Expression.LessThan(left, right);
Expression expNew = Expression.New(typeof(AnalysisChartSource));
LambdaExpression le = Expression.Lambda(left, pe);
MethodCallExpression whereCall = Expression.Call(
typeof(Queryable), "Where", new Type[] { data.ElementType },
data.Expression,
Expression.Lambda<Func<AnalysisChartSource, bool>>(e2, new ParameterExpression[] { pe }));
}
}
However……I have tried a similar approach for the Select statement, but just can’t get it to work as I need the Select() to populate both X and Y values of the AnalysisChartSource class, like this:
.Select(c => new AnalysisChartSource
{ Invoicedate = c.Invoicedate, yValue = c.yValue}).AsEnumerable();
How on earth can I build such an expression tree….or….possibly more to the point…..is there an easier way that I have missed entirely?
I find that the best way to work out how to build expression trees is to see what the C# compiler does. So here's a complete program:
using System;
using System.Linq.Expressions;
public class Foo
{
public int X { get; set; }
public int Y { get; set; }
}
class Test
{
static void Main()
{
Expression<Func<int, Foo>> builder =
z => new Foo { X = z, Y = z };
}
}
Compile that, open the results in Reflector and set the optimisation to .NET 2.0. You end up with this generated code for the Main method:
ParameterExpression expression2;
Expression<Func<int, Foo>> expression =
Expression.Lambda<Func<int, Foo>>(
Expression.MemberInit(
Expression.New((ConstructorInfo) methodof(Foo..ctor), new Expression[0]),
new MemberBinding[] { Expression.Bind((MethodInfo) methodof(Foo.set_X),
expression2 = Expression.Parameter(typeof(int), "z")),
Expression.Bind((MethodInfo) methodof(Foo.set_Y),
expression2) }
),
new ParameterExpression[] { expression2 });
Basically, I think Expression.MemberInit is what you're after.
Related
I have a class
class MyClass
{
string Foo { get; set; }
int Bar { get; set; }
//... Other properties
}
Now what I have is two expressions
Expression<Func<MyClass, string>> expr1 = x => x.Foo;
Expression<Func<MyClass, bool>> expr2 = x => x.Bar > 0;
Using this two expressions, I want to create an expression which is something like this
Expression<Func<MyClass, object>> expr = x => new { Foo = x.Foo, Baz = x.Bar > 0 };
In other words I want to combine two properties into one anonymous object using expression trees.
My problem is,
How do I create a similar expression from the given two expressions?
I want to use final expression in a join statement with entity framework query.
The bool part is complex and need to generate dynamically.
If any alternative idea to this, that would be helpful too.
I wrote a static method which will give appropriate predicate lambda using expression api for different type of fields.
static Func<T, bool> Process<T>(string type)
{
ParameterExpression parameter = Expression.Parameter(typeof(T));
Expression predicate = Expression.Constant(true);
if (type == "Start")
{
Expression prop = Expression.Property(parameter, type);
Expression filter = Expression.LessThan(prop, Expression.Constant(DateTime.Now));
predicate = Expression.AndAlso(predicate, filter);
}
//TODO: more if statments to come
var lambda = Expression.Lambda<Func<T, bool>>(predicate, parameter);
return lambda.Compile();
}
The above code works fine if I do a single query operation in linq like this:
var del = Process<MyClass>("Start");
var data = DbContext.MyClass.Where(del); //gets the result data
public class MyClass
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
public long Id { get; set; }
}
Now, if I do a join on the MyClass entity
var data = DbContext.MyClass
.Join(DbContext.Detail, mc => mc.Id, detail => detail.Id, (m, d) =>
new { m = m, d = d})
.Where(del);
The above lines are giving compile time error
Error CS1929 'IQueryable<<anonymous type: MyClass m, Detail d>>' does not contain a definition for 'Where' and the best extension method overload 'EnumerableRowCollectionExtensions.Where<MyClass>(EnumerableRowCollection<MyClass>, Func<MyClass, bool>)' requires a receiver of type 'EnumerableRowCollection<MyClass>'
I understand that .Where() now expects an anonymous type which has m and d but not sure how to resolve this.
I'm pretty new to Expression API. Not sure how to achieve.
I've tried to achieve that by creating anonymous type variable, but that is a variable and not the type itself to pass it to Process<T>().
The result of your Process method is a Where clause for objects of type MyClass, so you can't use it to filter anonymous objects { m, d }. Instead filter before the Join:
var data = DbContext.MyClass.Where(del);
.Join(DbContext.Detail,
mc => mc.Id,
detail => detail.Id,
(m, d) => new { m, d }
);
I want to execute linq method on iqueryable with an expression tree from function where I'm passing name of linq method and name of property. But my sample method works only with mapped properties. It throws an exception when I try to for example to find max of calculated property.
My classes:
public partial class Something
{
public int a { get; set; }
public int b { get; set; }
}
public partial class Something
{
public int calculated { get { return a * b; } }
}
Sample method:
public static object ExecuteLinqMethod(IQueryable<T> q, string Field, string Method)
{
var param = Expression.Parameter(typeof(T), "p");
Expression prop = Expression.Property(param, Field);
var exp = Expression.Lambda(prop, param);
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable),Method,types,q.Expression,exp);
return q.Provider.Execute(mce);
}
To be able to query on calculated properties, you have at least 2 options:
1) you store the calculated values in the db with the rows (or in a different table), and use them in your queries of course this requires datamodel change, and redundancy in data, but is the most performant way. But is not that exciting, so lets move on to
2) you need to be able to express the way you "calculate" the properties in a way that sql will understand, meaning the property needs to be replaced with a linq expression in the final query. I found in 2009 an amazing article from Eric Lippert on registering inline such properties, but I cannot find it anymore. As such here is a link to another, that has the same idea. Basically you define your calculation as an expression tree, and use the compiled version in your code.
To make it more convenient, you would attribute your property with a
[AttributeUsage(AttributeTargets.Property)]
class CalculatedByAttribute: Attribute
{
public string StaticMethodName {get; private set;}
public CalculatedByAttribute(string staticMethodName)
{
StaticMethodName = staticMethodName;
}
}
Like:
public partial class Something
{
[CalculatedBy("calculatedExpression")]
public int calculated { get { return calculatedExpression.Compile()(this); } }
public static Expression<Func<Something, int>> calculatedExpression = s => s.a * s.b;
}
(of course you can cache the compilation) :)
Then in your method, if the property has your attribute, you get the static property value, and use that in your queries. Something along:
public static object ExecuteLinqMethod<T>(IQueryable<T> q, string Field, string Method)
{
var propInfo = typeof(T).GetProperty(Field);
LambdaExpression exp;
var myAttr = propInfo.GetCustomAttributes(typeof(CalculatedByAttribute), true).OfType<CalculatedByAttribute>().FirstOrDefault();
if (myAttr != null)
exp = (LambdaExpression)typeof(T).GetField(myAttr.StaticMethodName, BindingFlags.Static | BindingFlags.Public).GetValue(null);
else
{
var param = Expression.Parameter(typeof(T), "p");
Expression prop = Expression.Property(param, Field);
exp = Expression.Lambda(prop, param);
}
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable),Method,types,q.Expression,exp);
return q.Provider.Execute(mce);
}
I have an entity.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
}
I want to create my own expression predicate. For that I have created a method that accepts property name and the value.
private static Expression<Func<Foo, bool>> Condition(string pName, object value)
{
var pe = Expression.Parameter(typeof(Foo), "foo");
var left = Expression.Property(pe, pName);
var right = Expression.Constant(value);
var equal = Expression.Equal(left, right);
var predicate = Expression.Lambda<Func<Foo, bool>>(equal, pe);
return predicate;
}
This is the predicate which works fine for a single condition.
using (var db = new MyEntities())
{
var predicate = Condition("Name", "foo");
var foos = db.Foos.Where(predicate).ToArray();
}
But when I tried to combine two conditions by following this post, it throws exception.
The parameter 'foo' was not bound in the specified LINQ to Entities
query expression.
using (var db = new MyEntities())
{
var cond1 = Condition("Name", "foo");
var cond2 = Condition("Code", "bar");
var body = Expression.AndAlso(cond1.Body, cond2.Body);
var predicate = Expression.Lambda<Func<Foo,bool>>(body, cond1.Parameters[0]);
var foos = db.Foos.Where(predicate).ToArray(); // exception
}
Please enlighten me.
The problem is that ParameterExpression in LINQ expressions is identified by reference equality, but the two Parameter objects are different references. (The name in ParameterExpression only exists for debugging purposes).
(If you reread the mentioned post, it says that the method that you tried would only work if both lambdas are defined on the same ParameterExpression object).
You have two big possibilities at this stage: either you define a way for the Condition function to accept a ParameterExpression object, or you create an ExpressionVisitor that will replace the original ParameterExpression with another. (Of course, given that you want to do an AndAlso, you could also conceivably chain two Where clauses, but that is less general.)
I have an Expression<Func<T,DateTime>> I want to take the DateTime part of the expression and pull the Month off of it. So I would be turning it into a Expression<Func<T,int>> I'm not really sure how to do this. I looked at the ExpressionTree Visitor but I can't get it to work like I need. Here is an example of the DateTime Expression
DateTimeExpression http://img442.imageshack.us/img442/6545/datetimeexpression.png
Here is an example of what I want to create
MonthExpression http://img203.imageshack.us/img203/8013/datetimemonthexpression.png
It looks like I need to create a new MemberExpression that is made up of the Month property from the DateTime expression but I'm not sure.
Yes, that's exactly what you want - and using Expression.Property is the easiest way to do that:
Expression func = Expression.Property(existingFunc.Body, "Month");
Expression<Func<T, int>> lambda =
Expression.Lambda<Func<T, int>>(func, existingFunc.Parameters);
I believe that should be okay. It works in this simple test:
using System;
using System.Linq.Expressions;
class Person
{
public DateTime Birthday { get; set; }
}
class Test
{
static void Main()
{
Person jon = new Person
{
Birthday = new DateTime(1976, 6, 19)
};
Expression<Func<Person,DateTime>> dateTimeExtract = p => p.Birthday;
var monthExtract = ExtractMonth(dateTimeExtract);
var compiled = monthExtract.Compile();
Console.WriteLine(compiled(jon));
}
static Expression<Func<T,int>> ExtractMonth<T>
(Expression<Func<T,DateTime>> existingFunc)
{
Expression func = Expression.Property(existingFunc.Body, "Month");
Expression<Func<T, int>> lambda =
Expression.Lambda<Func<T, int>>(func, existingFunc.Parameters);
return lambda;
}
}