创建一个动态Linq to EF表达式以将IQueryable选择到新类中并分配属性 [英] Create a Dynamic Linq to EF Expression to Select IQueryable into new class and assign properties
本文介绍了创建一个动态Linq to EF表达式以将IQueryable选择到新类中并分配属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试动态创建以下Linq的等效项.
I am trying to dynamically create the equivalent of the following Linq.
IQueryable<TypeOne> ones;
ones.Select(i => new TypeTwo { TwoProp = i.OneProp });
到目前为止,我有以下代码,但没有.
So far I have the following code but it isn't.
public class TypeOne
{
public string OneProp { get; set; }
}
public class TypeTwo
{
public string TwoProp { get; set; }
}
public static IQueryable<TypeTwo> Tester(IQueryable<TypeOne> data)
{
ConstructorInfo constructor = typeof(TypeTwo ).GetConstructor(new Type[] { });
Expression body = Expression.New(constructor);
ParameterExpression oneParam = Expression.Parameter(typeof(TypeOne), "one");
Expression prop1 = Expression.Property(oneParam, "OneProp");
ParameterExpression twoParam = Expression.Parameter(typeof(TypeTwo ), "two");
Expression prop2 = Expression.Property(twoParam, "TwoProp");
Expression assign = Expression.Assign(prop2, prop1);
body = Expression.Block(body, assign);
return data.Select(Expression.Lambda<Func<TypeOne, TypeTwo >>(body, oneParam));
}
但是我遇到以下异常:
其他信息:类型'System.String'的表达式不能用于返回类型'TypeTwo'
Additional information: Expression of type 'System.String' cannot be used for return type 'TypeTwo'
推荐答案
查看全文