获取具有上线值的行

时间:2017-10-25 09:51:28

标签: sql entity-framework linq

Users表中包含以下数据,

Id    Upline   Role    Username
----------------------------------
1      NULL      1       Admin
2      Admin     2       A10
3      A10       3       A1010
4      A1010     4       A101010
5      Admin     2        B2
6      B2        3        B3
7      B3        4        B4

要选择A行用户,结果将包含:

Id    Upline   Role    Username
----------------------------------
2      Admin     2       A10
3      A10       3       A1010
4      A1010     4       A101010

要选择B行用户,结果将包含:

Id    Upline   Role    Username
----------------------------------
5      Admin     2        B2
6      B2        3        B3
7      B3        4        B4

鉴于现在我有一个具有随机角色的用户,比如说 A101010,可以通过linq查询A101010上线用户吗?

Repository.Where(x=>x.Username==Upline && x.Role =Role+1);
//too bad this can only use to select exactly one upline right above the user.

然而在sql中,这可以通过以下方式实现:

WITH UserList  AS (
SELECT Username, Role, Upline from Users where Username = 'A101010'
UNION ALL
Select A.Username, Role, A.Upline
 FROM Users A
 INNER JOIN UserList X ON A.Username = X.Upline
) select * from UserList

期望的结果:

Id    Upline   Role    Username
----------------------------------
2      Admin     2       A10
3      A10       3       A1010

示例2 鉴于现在我有一个用户B3, 期望的结果:

Id    Upline   Role    Username
----------------------------------
5      Admin     2        B2

1 个答案:

答案 0 :(得分:0)

试试这个:

        class Userlist
        {
            public string Upline { get; set; }
            public int Role { get; set; }
            public string Username { get; set; }

            public Userlist(string upline, int role, string userName)
            {
                Upline = upline;
                Role = role;
                Username = userName;
            }
         }


        List<Userlist> users = new List<Userlist>()
        {
            new Userlist("Admin", 2, "a10"),
            new Userlist("a10", 3, "a1010"),
            new Userlist("Admin", 2, "B2"),
            new Userlist("b2", 3, "b3"),

        };

        var userList = users.Where(user => user.Username == "a1010");

        var q = (from u in users
                 join x in userList
            on u.Username equals x.Upline
            select u).Concat(userList).ToList();