Linq to Entities使用Lambda表达式和多个条件

时间:2017-03-02 23:23:45

标签: entity-framework lambda linq-to-entities

我试图在一个相当长的连接/选择链的末尾选择一个对象列表,使用Linq to Entities编写为Lambda表达式......这是我目前有以下两个语句。

    var formDefId = _unitOfWork.AsQueryableFor<FormTrack>()
        .Where(x => x.FormTrackId == formTrackId)
        .Select(x => x.FormDefId).First();

    var rules = _unitOfWork.AsQueryableFor<FormTrack>()
        .Where(x => x.FormTrackId == formTrackId)
        .Select(x => x.FormDef)
        .SelectMany(x => x.Events
            .Where(y => y.EventTypeId == 7))
        .Select(x => x.RuleGroup)
        .SelectMany(x => x.Rules)
        .SelectMany(x => x.RuleFormXmls
            .Where(y => y.FormDefId == formDefId));

我想做的是组合两个查询,并使用

返回的FormDefId
.Select(x => x.FormDef)

在最后的where子句中,而不必使用单独查询中的formDefId。

这是可能的吗?

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

使用查询语法编写此代码要容易得多。查询语法中的每个from都对应于lambda语法中的SelectMany。这允许您在范围内包含所有变量。

var rules = 
  from ft in _unitOfWork.AsQueryableFor<FormTrack>()
  from e in ft.FormDef.Events
  from r in e.RuleGroup.Rules
  from x in r.RuleFormXmls
  where ft.FormTrackId == formTrackId
  where e.EventTypeId == 7
  where x.FormDefId == ft.FormDefId
  select x