实体框架 - 参考搜索

时间:2017-09-15 06:43:05

标签: sql-server entity-framework linq

我试图从数据库中获取所有引用的值,直到最后一个值为空。

示例:如果我必须从下表中搜索ID - 1:

╔════╦════════╗
║ ID ║ RefID  ║
╠════╬════════╣
║ 1  ║ 2      ║
║ 1  ║ 3      ║
║ 2  ║ 4      ║
║ 3  ║ Null   ║
║ 4  ║ 6      ║
║ 5  ║ Null   ║
║ 6  ║ Null   ║
╚════╩════════╝

结果: 2 3 4 6

我试过了:

using (DbContext Db = new DbContext())
    {
        string ID = "1";
        List<string> ids = new List<string>();
        while (true)
        {
            List<string> t = Db.Test.Where(x => x.ID == ID).Select(x => x.RefID).ToList();
            foreach (string item in t)
            {
                if (item != null)
                {
                    ID = item;
                    ids.Add(item);
                }
                else
                {
                    break;
                }
            }
        }
    }

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

private void SearchRec(List<string> ids, List<string> result, DbContext Db)
{    
    var refs = Db.Test.Where(x => ids.Contains(x.ID) && x.RefID != null)
                 .Select(x => RefID).Distinct().ToList();
    var newRefs = refs.Except(result).ToList();        
    if(newRefs.Count > 0)
    {
        result.AddRange(newRefs);
        SearchRec(newRefs, result, Db);
    }           
}

public List<int> Search(string ID)
{
    var result = new List<string>();
    using (var Db = new DbContext())
    {
        SearchRec(new List<string> {ID}, result, Db);
    }
    return result;
}

<强>用法:

var answer = Search("1");