如何在实体框架

时间:2015-09-02 13:58:04

标签: c# entity-framework

我目前正在使用EF,我有两个表EmployeesOrders,因为Employee有多个Orders

我需要在EF中执行查询,该查询会为我提供所有Employees及其相关Orders的列表,但仅包含两个日期之间的查询。如果Employee在指定时间段内未执行任何Order,则其Orders列表将为空。

我想我需要从Employees DbSet开始查询,但是如何为Orders属性分配条件?

我试图这样做,但显然它没有用。

public List<Employee> GetAllByIdListAndDateRange(int[] ids, DateTime fromDate, DateTime toDate)
    {
        var query = _context.Set<Employee>().Where(a => ids.Contains(a.EmployeeID)).Include(a => a.Orders.Where(o.OrderDate <= toDate && o.OrderDate >= fromDate));

        return query.ToList();
    }

有任何帮助吗?我想我可能会错过这里非常简单的事情。

2 个答案:

答案 0 :(得分:2)

您无法在Include中使用Where谓词,但如果从Orders开始,则可以简化查询。

如果您再次考虑,您需要查询的是订单而不是员工。

var query = _context.Set<Orders>()
                    .Where(o => o.OrderDate <= toDate &&
                                o.OrderDate >= fromDate && 
                                ids.Contains(o.EmployeeID))
                    .Include(e => e.Employee));

答案 1 :(得分:1)

尝试替换

myQuery.Include(x=>x.Y).Load();

by:

myQuery.Load();
myQuery.SelectMany(x=>x.y).Where( ....).Load();
相关问题