LINQ中的递归/分层查询

时间:2016-08-17 03:13:17

标签: c# sql-server entity-framework linq hierarchical-data

情景是,

即时通讯使用EntityFrame工作6.我有一个数据库有下面结构的表。

cat_id     geo_id     parent_id geo_name
   Root       1       NULL      Pakistan
   Province   2        1        Punjab
   District   3        2        Attock
   City       4        3        Attock
   City       5        3        Fateh Jang
   City       6        3        Hasan Abdal

如您所见,表格具有关系形式的分层数据。

我想要遍历此层次结构,想要特定的父级别,如果我在geo_id 6,那么我想转到parent_id 3并获取值Attock或者想要转到{{1并希望得到值parent_id 2

故事的道德是,站在任何一个孩子身上,希望遍历到指定的父母或祖父母,而不是整个等级。下面是我尝试过的代码,但它只给了我直接的父母。

更简单地说,想要一个LINQ查询,它将返回指定父级或祖父级的名称,例如。我可以问我的问题,“嘿!我Punjab,告诉我我的Hasan Abdal(City)

Province

请参阅下面的完整代码,它在LINQ查询的Province = (from cp in db.geo_hierarchy join mp in db.geo_hierarchy on cp.parent_id equals mp.geo_id where cp.geo_name == risk.geo_hierarchy.geo_name select mp.geo_name).FirstOrDefault() 子句

中使用
select

帮助我,先谢谢

1 个答案:

答案 0 :(得分:0)

试试这个:

var geo_hierarchy = new []
{
    new { cat_id = "Root", geo_id = 1, parent_id = (int?)null, geo_name = "Pakistan", },
    new { cat_id = "Province", geo_id = 2, parent_id = (int?)1, geo_name = "Punjab", },
    new { cat_id = "District", geo_id = 3, parent_id = (int?)2, geo_name = "Attock", },
    new { cat_id = "City", geo_id = 4, parent_id = (int?)3, geo_name = "Attock", },
    new { cat_id = "City", geo_id = 5, parent_id = (int?)3, geo_name = "Fateh Jang", },
    new { cat_id = "City", geo_id = 6, parent_id = (int?)3, geo_name = "Hasan Abdal", },
};

var map = geo_hierarchy.ToDictionary(x => x.geo_id);

Func<int, string, string> up = null;
up = (geo_id, cat_id) =>
{
    var record = map[geo_id];
    return
        record.cat_id == cat_id
            ? record.geo_name
            : (record.parent_id.HasValue
                ? up(record.parent_id.Value, cat_id)
                : null);
};

var result = up(5, "Province"); // -> "Punjab"