问题
Im using the DynamicQueryable.Select() // dynamic select library
The only docu I have found so far is System.Linq.Dynamic docu
I have this query with anonymous return type which works.
var result = Context.Set<TPocoText>().Where((Expression<Func<TPocoText, bool>>) whereLambda)
.OrderByDescending(t => t.RowVersion).Skip(skip).Take(take)
.Select("new (m1,m2,Nav1) ");
and this works like select(t=> new {t.m1,t.m2,t.Nav1}) as expected
my Question How can it do the equivalent of select(t=> new {t,t.Nav1})
i tried .Select("new (it,Nav1) ") and .Select("new (this,Nav1) ")
the result was a parse error member not found. Anybody know this dynamic string parsing API?
OR the equivalent Expression building syntax is also an option.
NOTE:The Nav Property ForSourceRecord is only known at runtime otherwise i would just use the normal lambda expression.
回答1:
This cannot be done using anon types. The compiler just doesn't have the information needed to work, especially with the free text/string approach.
Try this...
var param = System.Linq.Expressions.Expression.Parameter(typeof(TPocoText));
var init = System.Linq.Expressions.Expression.MemberInit(
System.Linq.Expressions.Expression.New(typeof(Foo)),
new []{
System.Linq.Expressions.Expression.Bind(GetMemberInfo((Foo f) => f.Nav), System.Linq.Expressions.Expression.PropertyOrField(param, "NameOfPropertyToBindToNav")),
System.Linq.Expressions.Expression.Bind(GetMemberInfo((Foo f) => f.M1), System.Linq.Expressions.Expression.PropertyOrField(param, "M1")),
}
);
var result = Context.Set<TPocoText>().Where((Expression<Func<TPocoText, bool>>) whereLambda)
.OrderByDescending(t => t.RowVersion).Skip(skip).Take(take)
.Select(System.Linq.Expressions.Expression.Lambda<Func<TPocoText, Foo>>(init, param));
public class Foo
{
public string Nav {get;set;}
public string M1 {get;set;}
}
public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression)
{
var member = expression.Body as MemberExpression;
if (member != null)
return member.Member;
throw new ArgumentException("Expression is not a member access", "expression");
}
来源:https://stackoverflow.com/questions/17333325/dynamic-select-entityframework-and-system-linq-dynamic