第一个版本在 IQueryable 上使用时不起作用。 (仅在 IEnumerable 上)
滚动到本文中的最终版本以获取 IQueryable-working 版本。
public class ComplexType
{
public Guid Id { get; set; }
public SimpleType Property1 { get; set; }
public SimpleType Property2 { get; set; }
public static Expression<Func<complex_type_entity, ComplexType>> CreateExpression()
{
var compiledSimpleTypeFnc = SimpleType.CreateExpression().Compile();
return arg => new ComplexType
{
Id = arg.id,
Property1 = compiledSimpleTypeFnc(arg.property1),
Property2 = compiledSimpleTypeFnc(arg.property2)
};
}
}
或者如果你真的想把它作为一个表达式保留到最后:
public class ComplexType
{
public Guid Id { get; set; }
public SimpleType Property1 { get; set; }
public SimpleType Property2 { get; set; }
public static Expression<Func<complex_type_entity, ComplexType>> CreateExpression()
{
var expr = SimpleType.CreateExpression();
return arg => new ComplexType
{
Id = arg.id,
Property1 = expr.Compile()(arg.property1),
Property2 = expr.Compile()(arg.property2)
};
}
}
编辑:以下代码适用于实体框架。
using System;
using System.Linq.Expressions;
using ConsoleApplication2;
using System.Linq;
class Program2
{
public static void Main(string[] args)
{
using (var db = new TestEntities())
{
var exp = db.complex_type_entity.Select(ComplexType.CreateExpression()).First();
}
}
}
public class SimpleType
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public static Expression<Func<simple_type_entity, SimpleType>> CreateExpression()
{
var parameterExpr = Expression.Parameter(typeof(simple_type_entity), "p0");
return Expression.Lambda<Func<simple_type_entity, SimpleType>>(CreateExpression(parameterExpr), parameterExpr);
}
public static MemberInitExpression CreateExpression(Expression sourceExpr)
{
return Expression.MemberInit(
Expression.New(typeof(SimpleType)),
Expression.Bind(typeof(SimpleType).GetProperty("Id"), Expression.Property(sourceExpr, "id")),
Expression.Bind(typeof(SimpleType).GetProperty("Name"), Expression.Property(sourceExpr, "name")),
Expression.Bind(typeof(SimpleType).GetProperty("Description"), Expression.Property(sourceExpr, "desc")));
}
}
public class ComplexType
{
public Guid Id { get; set; }
public SimpleType Property1 { get; set; }
public SimpleType Property2 { get; set; }
public static Expression<Func<complex_type_entity, ComplexType>> CreateExpression()
{
var parameterExp = Expression.Parameter(typeof(complex_type_entity), "p0");
return Expression.Lambda<Func<complex_type_entity, ComplexType>>(
Expression.MemberInit(
Expression.New(typeof(ComplexType)),
Expression.Bind(typeof(ComplexType).GetProperty("Id"), Expression.Property(parameterExp, "id")),
Expression.Bind(typeof(ComplexType).GetProperty("Property1"), SimpleType.CreateExpression(Expression.Property(parameterExp, "simple_type_entity"))),
Expression.Bind(typeof(ComplexType).GetProperty("Property2"), SimpleType.CreateExpression(Expression.Property(parameterExp, "simple_type_entity1")))),
parameterExp);
}
}