IEnumerable<ViewEmployees> employees = from e in db.Users
join p in db.Users on e.ParentID equals p.Id
select new ViewEmployees
{
EmployeeName = e.Name,
EmployeeID = e.Id,
EmployeeCode = e.UserName,
ParentID = e.ParentID,
ParentName = p.Name
};
编写此查询是为了选择父级的名称并显示所有员工..
它只显示员工如何拥有父ID ..
我希望谁拥有parentId
而谁不拥有......
答案 0 :(得分:0)
生成两个集合的左外连接的第一步是使用组连接执行内连接。 (有关此过程的说明,请参见如何:执行内部联接(C#编程指南)。)在此示例中,Person对象列表基于与Pet.Owner匹配的Person对象内部连接到Pet对象列表。 。 第二步是将第一个(左)集合的每个元素包含在结果集中,即使该元素在右集合中没有匹配项也是如此。这是通过在组连接的每个匹配元素序列上调用DefaultIfEmpty来实现的。在此示例中,在匹配Pet对象的每个序列上调用DefaultIfEmpty。如果任何Person对象的匹配Pet对象的序列为空,则该方法返回包含单个默认值的集合,从而确保每个Person对象都在结果集合中表示。
public static void LeftOuterJoinExample()
{
Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };
Pet barley = new Pet { Name = "Barley", Owner = terry };
Pet boots = new Pet { Name = "Boots", Owner = terry };
Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
Pet daisy = new Pet { Name = "Daisy", Owner = magnus };
// Create two lists.
List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };
foreach (var v in query)
{
Console.WriteLine("{0,-15}{1}", v.FirstName + ":", v.PetName);
}
}
答案 1 :(得分:0)
您可以像这样在临时变量User
中获取父parent
:
var employees = from e in db.Users
let parent = db.Users.FirstOrDefault(p => e.ParentID == p.Id)
select new ViewEmployees
{
EmployeeName = e.Name,
EmployeeID = e.Id,
EmployeeCode = e.UserName,
ParentID = e.ParentID,
ParentName = parent.Name
};
您不需要检查parent != null
,因为该语句已转换为SQL,不受空值的影响。
如果User
具有导航属性Parent
,则会更容易。