Linq查询WHERE一个字段是> =父表中的另一个字段?

时间:2016-09-19 03:54:26

标签: c# entity-framework linq

我该如何翻译:

SELECT ExchangeTypes.*, Fixtures.*
FROM Fixtures 
INNER JOIN ExchangeTypes ON Fixtures.ExchangeTypeId = ExchangeTypes.Id 
WHERE ExchangeTypes.LayOdds <= Fixtures.BackOdds

进入Linq - 这是我的基本查询:

        {
        var fixtureDtos = _context.Fixtures   //.Where(c => c.BackOdds >= c.ExchangeType.LayOdds) 
            .Include(c => c.ExchangeType)
            .ToList()
            .Select(Mapper.Map<Fixture, FixtureDto>);

        return Ok(fixtureDtos);
        }

请注意,Fixture和Exchange类型之间已经设置了导航属性(多对1)。

2 个答案:

答案 0 :(得分:1)

var fixtureDtos = (from m in _context.Fixtures
                  join n in _context.ExchangeTypes
                  on m.ExchangeTypeId = n.Id
                  where n.BackOdds > m.BackOdds
                  select new {/*add columns needed from m and n here*/}).ToList();

答案 1 :(得分:0)

我设法在EF导航属性中执行此操作。我在评论的代码中处于正确的位置,但忘记确保所比较的两个字段属于同一类型(在为测试目的而改变一个字段之后)。

这是导航属性linq代码:

        {
        var fixtureDtos = _context.Fixtures.Where(c => c.BackOdds >= c.ExchangeType.LayOdds)  
            .Include(c => c.ExchangeType)
            .ToList()
            .Select(Mapper.Map<Fixture, FixtureDto>);

        return Ok(fixtureDtos);
    }