我试图建立一个简单的LambdaExpression包括MemberExpression.如果我使用System.Linq.Expressions API(例如MakeMemberAccess)显式创建了MemberExpression ,我将在我调用Compile()时得到错误"InvalidOperationExpression变量'x'引用范围'',但它没有定义" LambdaExpression.
例如,这是我的代码
Expression<Func<Customer, string>> expression1, expression2, expression3;
Func<Customer, string> fn;
expression1 = (x) => x.Title;
fn = expression1.Compile();//works
fn(c);
MemberExpression m;
m = Expression.MakeMemberAccess(
Expression.Parameter(typeof(Customer), "x"), typeof(Customer).GetProperty("Title"));
expression2 = Expression.Lambda<Func<Customer, string>>(m,
Expression.Parameter(typeof(Customer), "x"));
m = Expression.Property(Expression.Parameter(typeof(Customer),"x"), "Title");
expression3 = Expression.Lambda<Func<Customer, string>>(m,
Expression.Parameter(typeof(Customer), "x"));
fn = expression3.Compile();//InvalidOperationExpression variable 'x' referenced from scope '', but it is not defined
fn = expression2.Compile();//InvalidOperationExpression variable 'x' referenced from scope '', but it is …
Run Code Online (Sandbox Code Playgroud) 我必须做一个搜索来返回一个值,我要做的是两个字段相乘的总和.我有以下代码:
internal double TotalRes(long Id)
{
double total = 0;
Reserve rAlias = null;
var query = Session.QueryOver<Item>();
query = query.JoinAlias(e => e.Reserve, () => rAlias);
query = query.Where(() => rAlias.Id == Id);
query = query.Select(Projections.Sum<Item>(acct => acct.Ammount * acct.Wight));
object result = query.UnderlyingCriteria.UniqueResult();
if (result != null)
total = Convert.ToDouble(result);
return total;
}
Run Code Online (Sandbox Code Playgroud)
它给出以下错误:
变量'acct'类型'tem'在范围''中引用,但未设置
我怎样才能归还这个值?