SQL到Linq转换问题

时间:2014-07-01 19:01:47

标签: c# sql linq

有人可以帮助我将sql语句转换为linq吗?我可以做非常基本的陈述,但在使用linq处理几个连接和联合时我感到困惑。这是我要转换的SQL语句:

SELECT UserName, UPPER(FirstName) as FirstName, UPPER(LastName) as LastName 
FROM PDDA.dbo.Users 
WHERE Cono = " & Cono & " 

UNION 

SELECT u.UserName, UPPER(FirstName) as FirstName, UPPER(LastName) as LastName 
FROM PDDA.dbo.GroupMembers g 
JOIN PDDA.dbo.UserGroups ug
  on ug.groupid = g.groupid 
JOIN PDDA.dbo.Users u 
  on u.username = g.username 
WHERE ug.GroupName = 'AP Department' OR ug.GroupName = 'MIS' 
ORDER BY LastName, FirstName")

到目前为止,这是我的尝试:

    var userDb = new PDDAEntities();
    var users =
        ((from user in userDb.Users select user.UserName).Union(from gm in userDb.GroupMembers
            join ug in userDb.UserGroups on gm.GroupID equals ug.GroupID
            (from u in userDb.Users join ))
            select user.UserName;

2 个答案:

答案 0 :(得分:2)

分解它变得更容易。第一步,第一部分:

SELECT UserName, UPPER(FirstName) as FirstName, UPPER(LastName) as LastName 
FROM PDDA.dbo.Users WHERE Cono = " & Cono & " 

这很简单。

var query1 = from u in Users where u.Cono == yourCono 
     select new { u.UserName, u.FirstName, u.LastName }

第二部分有点难,但并不多。

SELECT u.UserName, UPPER(FirstName) as FirstName, UPPER(LastName) as LastName 
FROM PDDA.dbo.GroupMembers g 
JOIN PDDA.dbo.UserGroups ug on ug.groupid = g.groupid 
JOIN PDDA.dbo.Users u on u.username = g.username 
WHERE ug.GroupName = 'AP Department' OR ug.GroupName = 'MIS' 
ORDER BY LastName, FirstName

这看起来像这样(未经测试,但应该类似):

var query2 = from gm in GroupMembers 
   join ug in UserGroups on gm.groupid equals ug.groupid
   join u in Users on gm.UserName equals u.UserName
   where ug.GroupName == 'AP Department' || ug.GroupName == 'MIS'
   orderby u.LastName, u.FirstName
   select new { UserName = u.UserName, FirstName = u.FirstName, LastName = u.LastName }

然后将它们组合起来。

var query3 = query1.Union(query2);

我不确定订单是否按订单加入,如果是,那么你只需要这样做:

var query3 = query1.Union(query2).OrderBy(x => x.LastName).ThenBy(x => x.FirstName);

您可以从上面的query2中删除OrderBy。

编辑:

基于Striplings Query,您甚至可以这样做(假设您已配置UserGroups导航属性):

from u in userDb.Users
where u.UserGroups.Any(ug => ug.GroupName == "AP Department" || ug.GroupName == "MIS") 
      || u.Cono == yourCono
orderby u.LastName, u.FirstName
select new {u.UserName, u.FirstName, u.LastName}

当时根本不需要工会。

答案 1 :(得分:1)

我发现LINQ比SQL更直观,并且大多数人的困难来自于尝试直接翻译而不是让LINQ为他们工作。假设您的表关系设置正确,您可以执行以下操作:

from u in userDb.Users
where u.UserGroups.Any(ug => ug.GroupName == "AP Department" || ug.GroupName == "MIS")
orderby u.LastName, u.FirstName
select new {u.UserName, u.FirstName, u.LastName};