我希望将3个表作为对象列表连接起来。这是我的三个表:
员工
部门
类别
Employee DepartmentID和CategoryID用于联接Department和Category Table。
这是我的Linq Join的外观
var result = from e in Employee.GetAllEmployees()
join d in Department.GetAllDepartments() on e.DepartmentID equals d.ID
join c in Cateory.GetAllCategories() on e.CategoryID equals c.ID
into eGroup
from c in eGroup.DefaultIfEmpty()
select new
{
Employee =e,
Department = d ==null? new Department() : d,
Cateory = c
};
我的问题是,我得到了两行不同的Employee ID = 1行,这是因为ID = 1的两个不同类别
我想将两个类别都放在同一个Employee节点中。员工ID = 1基本上是两个类别。
预期结果: CategoryA和CategoryB与员工标记相关。
我该如何实现?
感谢您的帮助!
这是重现我目前所拥有代码的代码。
class Program
{
static void Main(string[] args)
{
var result = from e in Employee.GetAllEmployees()
join d in Department.GetAllDepartments() on e.DepartmentID equals d.ID
join c in Cateory.GetAllCategories() on e.CategoryID equals c.ID
into eGroup
from c in eGroup.DefaultIfEmpty()
select new
{
Employee =e,
Department = d ==null? new Department() : d,
Cateory = c
};
Console.WriteLine("Hello World!");
Console.ReadLine();
}
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public int DepartmentID { get; set; }
public int CategoryID { get; set; }
public static List<Employee> GetAllEmployees()
{
return new List<Employee>()
{
new Employee { EmployeeID = 1, Name = "Mark", DepartmentID = 1, CategoryID = 1 },
};
}
}
public class Department
{
public int ID { get; set; }
public string DepartmentName { get; set; }
public static List<Department> GetAllDepartments()
{
return new List<Department>()
{
new Department { ID = 1, DepartmentName = "TECH"},
new Department { ID = 2, DepartmentName = "HR"},
};
}
}
public class Cateory
{
public int ID { get; set; }
public string CategoryName { get; set; }
public static List<Cateory> GetAllCategories()
{
return new List<Cateory>()
{
new Cateory { ID = 1, CategoryName = "CategoryA"},
new Cateory { ID = 1, CategoryName = "CategoryB"},
new Cateory { ID = 2, CategoryName = "CategoryC"},
};
}
}
}
答案 0 :(得分:1)
我真的没有办法进行测试,但是您应该可以通过更新查询来进行左联接
var result = from e in Employee.GetAllEmployees()
join d in Department.GetAllDepartments() on e.DepartmentID equals d.ID into d_def
from d in d_def.DefaultIfEmpty()
join c in Cateory.GetAllCategories() on e.CategoryID equals c.ID into c_def
from c in c_def.DefaultIfEmpty())
select new
{
Employee =e,
Department = d ==null? new Department() : d,
Cateory = c
};
答案 1 :(得分:-1)