LINQ以最佳方式加入,没有多个from子句

时间:2010-12-29 18:37:22

标签: c# linq linq-to-entities

我是LINQ的新手。这是我的Linq查询

var users = from UserTbl in entity.User
            from grpTbl in entity.Group
            from role in entity.Role
            where grpTbl.groupID == UserTbl.groupID&& UserTbl.userID==role.userID 
            select new Contract.User()
            {
                UserId = UserTbl.userID,
                UserName = UserTbl.userName,
                FirstName = UserTbl.firstName,
                LastName = UserTbl.lastName,
                GroupId = grpTbl.groupID,
                GroupName =grpTbl.groupName,
                DesignationID = role.roleID    
            };

如何以最佳方式编写此查询?

1 个答案:

答案 0 :(得分:3)

很好。但我更喜欢joins,因为它们可以从where子句中删除“匹配”表达式,因此只有“真正的”过滤仍然存在。

var users = from UserTbl in entity.User
            join grpTbl in entity.Group on grpTbl.groupID equals groupId            
            join role in entity.Role on UserTbl.userID equals role.userID 
            select new Contract.User()
            {
                UserId = UserTbl.userID,
                UserName = UserTbl.userName,
                FirstName = UserTbl.firstName,
                LastName = UserTbl.lastName,
                GroupId = grpTbl.groupID,
                GroupName =grpTbl.groupName,
                DesignationID = role.roleID    
            };