问题描述
我是linq的新手,我正在寻找一种方式来为父母返回父母和一个List(孩子)以及所有这些孩子。我有一个位置表,其中包含字段 LocationID
, ParentLocationID
, LOCATIONNAME
。数据样本可能如下所示:
I'm new to linq and am trying to find a way to return the parent and a List (children) and all those children, for a given parent. I have a Locations table with the fields LocationID
, ParentLocationID
, LocationName
. A sample of the data could look like this:
ABC
--ABC1
--ABC2
----DEF1
----DEF2
----DEF3
--ABC3
----DEF4
------GHI1
------GHI2
----DEF5
--ABC4
...
如果选择的父级是ABC,那么我想返回所有的行,因为所有的子项都在它之下。但是,如果我选择父母ABC3,它将返回DEF4,GHI1,GHI2,DEF5。
Given that data, if the selected parent is 'ABC', I want to return all the rows because all children are under it. However, if I selected the parent 'ABC3', it would return DEF4, GHI1, GHI2, DEF5.
我已经研究了这些SO问题,但仍然感到困惑如何创建此语句:
I've looked into these SO questions but am still confused on how to create this statement(s):
这是我尝试过的但是出现错误:
Here's what I've tried but am getting an error:
public ActionResult Index()
{
var loc = GetChild(346);
return View(loc);
}
public IEnumerable<Location> GetChild(int id)
{
DBEntities db = new DBEntities();
var locations = db.Locations.Where(x => x.ParentLocationID == id || x.LocationID == id).Union(
db.Locations.Where(x => x.ParentLocationID == id).SelectMany(y => GetChild(y.LocationID)));
return locations;
}
而位置
课程是:
public class Location
{
public Location();
public virtual ICollection<SimSystem> SimSystems { get; set; }
public virtual ICollection<LocationAddress> LocationAddresses { get; set; }
public virtual LocationType LocationType { get; set; }
public virtual ICollection<CustomerUser> CustomerUsers { get; set; }
public virtual ICollection<AppUserLocation> AppUserLocations { get; set; }
public int LocationTypeID { get; set; }
public DateTime? InstallDate { get; set; }
public string AltPhone { get; set; }
public string OfficePhone { get; set; }
public int? PrimaryAddressID { get; set; }
public int? ParentLocationID { get; set; }
public string LocationName { get; set; }
public string LocationName2 { get; set; }
public int LocationID { get; set; }
public virtual Address Address { get; set; }
}
错误是:
LINQ to Entities不会识别该方法,并且此方法无法转换为存储表达式。
推荐答案
你可以尝试这个..
public IEnumerable<Location> GetChild(int id)
{
DBEntities db = new DBEntities();
var locations = db.Locations.Where(x => x.ParentLocationID == id || x.LocationID == id).ToList();
var child = locations.AsEnumerable().Union(
db.Locations.AsEnumerable().Where(x => x.ParentLocationID == id).SelectMany(y => GetChild(y.LocationId))).ToList();
return child;
}
这篇关于递归linq获得无限儿童的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!