我有以下代码来创建表达式:
Expression<Func<Process, bool>> exp = null;
if (condition)
{
exp = x => x.Hierarchy.StartWith(hierarchy) && x.Level == 2;
}
/*
other conditions that modify the exp variable
*/
else
{
exp = x => x.Hierarchy == hierarchy && x.Level == 3;
}
根据某些条件,此查询可能会有所不同。我将在以下查询中使用此表达式,但是,我想exp
在linq
查询中将表达式变量作为样本:
var query = from p in queryable
join c in confQueryable on p.Id equals c.Id
where p.ParentId == parentProcessId && exp // AND exp here...
let hasChild = p.Processes.Any()
select new ViewModel
{
Code = p.Code,
Text = string.Format("{0}: {1}", c.Name, p.Name), // use c variable
ParentId = p.Id,
Value = p.Id.ToString(),
HasChildren = hasChild, // use hasChild variable
};
我无法将其转换为linq方法,因为我返回的ViewModel
不是实体。如果这样做,我将不知道如何在linq方法中使用join
andlet
命令。
该查询将使用NHibernate在数据库中执行。
如何Expression<Func<T, bool>>
在Linq
查询中合并?
谢谢。
为什么不能使用像这样的链方法
var query =
queryable
.Where(exp)
.Join(confQueryable, p => p.Id, c => c.Id, (p, c) => new {p, c})
.Where(@t => p.ParentId == parentProcessId)
.Select(@t => new {@t, hasChild = p.Processes.Any()})
.Select(@t => new ViewModel
{
Code = p.Code,
Text = string.Format("{0}: {1}", c.Name, p.Name), // use c variable
ParentId = p.Id,
Value = p.Id.ToString(),
HasChildren = hasChild, // use hasChild variable
});
我不了解nHibernate,但是对于Entity Framework,这种linq查询应该可以工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句