LINQ web api代码中的递归查询

本文关键字:递归查询 代码 web api LINQ | 更新日期: 2023-09-27 18:29:01

需要在我的Web Api代码中通过LINQ编写递归查询。表格结构如下:

create table dbo.Test(
ID int primary key not null,
Name nvarchar(20) not null,
[Description] nvarchar(20) not null,
Parent_ID int)
ID      Name            Description     Parent_ID
1001    BusinessUnit    BU              NULL
1002    BrandUnit       Brand           1001
1003    Branch1         LondonBranch1   1002
1004    Branch2         LondonBranch2   1002
1005    Branch3         LondonBranch3   1002

我的Web API代码如下:

public class TestController : ApiController
    {
    public class TestDTO
    {
        public string Name { get; set; }
        public string Desc { get; set; }
    }
    public TestDTO Get()
    {
        using (var db = new SampleEntities())
        {
            var hardcodedBusinessUnitID=1001;
            var xx = db.Tests.FirstOrDefault(x => x.ID.Equals(hardcodedBusinessUnitID)).ID;
            List<int> list=new List<int>();
            list.Add(xx);
            var idFromUI=1009;
            return new TestDTO
            {
                Name = list.Contains(idFromUI) ? "Match Found" : string.Empty,
                Desc = "Blah Blah"
            };
        }
    }
}

不知何故,我需要通过LINQ查询从数据库中获取ID 1001的所有子级(因为1001有一个id为1002的子级,它还有三个id为10031004和1005的子级),并将它们绑定到list中。

张贴我将从UI获得ID,并检查UI中的ID是否存在于该列表中。

我做不到,因为我对LINQ不是很精通。

请专家帮忙。

LINQ web api代码中的递归查询

您需要一个用于查找子项的临时项目列表;你清空列表,把孩子们放在列表里,然后重复。可能是这样的:

var parent = db.Tests.FirstOrDefault(x => x.ID.Equals(hardcodedBusinessUnitID)).ID;
// a list of the type of your object, to store all the items
var items = new List<Test>();
items.Add(parent)
// make a new list that will be used to search the table
searchItems = new List<Test>(items);
while (searchItems.Any())
{
    var ids = searchItems.Select(i => i.ID).ToList();
    searchItems = db.Tests.Where(t => 
        t.Parent_ID.HasValue && ids.Contains(t.Parent_ID.Value)).ToList();
    items.AddRange(searchItems);
}
List<int> list = items.Select(i => i.ID).ToList();

您可能会有不同的想法。从UI中查找的id开始搜索,然后在层次结构中向上搜索,直到找到没有父级的测试记录。然后将没有父ID的测试记录与硬编码的ID进行比较。如果它们匹配,则UI中的ID是子ID;否则不会。

var t = db.Tests.SingleOrDefault(x => x.ID == idFromUI);
if(t != null){
    int? parentId = t.Parent_ID;
    int rootParentId = -1;
    while(parentId != null){
        var currentTest = db.Tests.SingleOrDefault(x => x.ID == parentId);
        if(currentTest != null){
            parentId = currentTest.Parent_ID;
            rootParentId = currentTest.ID;
        }
        else{
           parentId = null;
        }
    }
    if(rootParentId == hardcodedBusinessUnitID){
        return new TestDTO
        {
            Name = "Match Found",
            Desc = "Blah Blah"
        };
    }        
}
return new TestDTO
        {
            Name = string.Empty,
            Desc = "Blah Blah"
        };