【发布时间】:2012-03-22 03:17:00
【问题描述】:
比如说,我有这些在派生类中被覆盖的属性。
protected virtual Expression<Func<TEntity, long>> GetIDExpr { get; }
protected virtual Expression<Func<TEntity, string>> GetNameExpr { get; }
protected virtual Expression<Func<TEntity, long>> GetValueExpr { get; }
现在说我有这门课
public class MyData
{
public long ID { get; set; }
public string Name { get; set; }
public long Value { get; set; }
}
现在,在基类中,我将如何创建一个 Expression<Func<TEntity, MyData>>,当它被调用时,它将填充每个字段并允许我创建一个返回 IEnumerable<MyData> 的方法?
我想避免使用Invoke,因为我只想从数据库中选择这 3 个字段。
注意:就本示例而言,将每个属性视为每次调用它都会返回相同的表达式实例,而不是每次都创建一个新实例。
编辑:
这是我的尝试,但不起作用:
public IEnumerable<MyData> GetAllData(IQueryable<TEntity> table) {
ParameterExpression parameter = Expression.Parameter(typeof(TEntity), "obj");
List<MemberBinding> bindings = new List<MemberBinding> {
Expression.Bind(typeof(MyData).GetProperty("ID"), GetIDExpr.Body),
Expression.Bind(typeof(MyData).GetProperty("Name"), GetNameExpr.Body),
Expression.Bind(typeof(MyData).GetProperty("Value"), GetValueExpr.Body),
};
var selector = Expression.MemberInit(Expression.New(typeof(MyData).GetConstructor(Type.EmptyTypes)), bindings);
var getBar = Expression.Lambda<Func<TEntity, MyData>>(selector, parameter);
return table.Select(getBar);
}
这里我在执行查询时得到一个 ArgumentException,说
参数“obj”未绑定在指定的 LINQ to Entities 查询表达式中。
我认为这意味着使用.Body 作为值表达式将不起作用,因为不再有参数。但是,如果我不使用.Body,我会在.Bind 方法上得到一个异常
参数类型不匹配
【问题讨论】:
标签: c# linq expression