LINQ查询可以使用外键从其他表中获取值

时间:2016-04-09 08:45:43

标签: c# sql-server asp.net-mvc linq

是否可以对下面的表Timeunit进行LINQ方法查询,并使用外键Employee或Order从某些行获取数据?

这就是我想要实现的目标。在视图中,我使用Timeunit,Employee和Order传递ViewModel。在视图中的Order的ForEach循环中,我尝试让所有使用该订单的员工。这有可能还是我在这里想错了?

@foreach (var item1 in Model.orderlist)
{
@Model.timeunitlist.Where(x => x.OrderID == item1.EmployeeID).FirstName ????
}

public class Timeunit
{
public int ID { get; set; }
public int Week { get; set; }
public int HoursPerWeek { get; set; }
public int EmployeeID { get; set; }
public int? OrderID { get; set; } 
public virtual Employee Employee { get; set; }
public virtual Order Order { get; set; }
}

编辑1:其他两个表

public class Order
{
public int ID { get; set; }
public string Name { get; set; }
public int? ManufacturerID { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}

public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int EmployeeNumber { get; set; }
public virtual ICollection<Timeunit> Timeunits { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}

编辑2:视图模型

public class ViewModel
{
    public List<Timeunit> timeunitList = new List<Timeunit>();
    public List<Employee> employeeList = new List<Employee>();
    public List<Order> orderList = new List<Order>();
}

我需要的是每个订单,我需要列出每个订单与特定周匹配的所有时间单位,并显示每个员工在每个订单中工作的小时数

1 个答案:

答案 0 :(得分:1)

要显示按Timeunit分组的Order集合,您需要使用linq .GroupBy()子句。首先创建视图模型以表示要在视图中显示的内容

public class OrderVM
{
    public string Name { get; set; }
    public IEnumerable<EmployeeVM> Employees { get; set; }
}
public class EmployeeVM
{
    public string Name { get; set; }
    public int Hours { get; set; }
}

并在控制器中,使用linq查询将数据投影到视图模型中

IEnumerable<OrderVM> model = db.Timeunits
    .Where(x => x.Week == 1)
    .GroupBy(x => x.OrderID)
    .Select(x => new OrderVM()
    {
        Name = x.FirstOrDefault().Order.Name,
        Employees = x.Select(y => new EmployeeVM()
        {
            Name = y.Employee.Name,
            Hours = y.HoursPerWeek
        })
    }).AsEnumerable();
return View(model);

然后在视图中

@model IEnumerable<OrderVM>
@foreach (var order in Model)
{
    @Html.DisplayFor(m => order.Name)
    foreach(var employee in order.Employees)
    {
         @Html.DisplayFor(m => employee.Name)
         @Html.DisplayFor(m => employee.Hours)
    }
}