如何将多个SQL左连接转换为Linq-To-SQL

时间:2010-06-20 15:11:20

标签: sql linq linq-to-sql

我有一个用户表,一个user_items表,一个user_to_group表和一个组表。

如何将以下SQL查询转换为正确的Linq-to-sql查询?

select user.username, user.email, user_items.item_number, item_types.desc, [group].name from user
left join user_items on user.user_id = user_items.user_id
left join item_types on user_items.item_type_id = item_types.item_type_id
left join user_to_group on user.user_id = user_to_group.user_id
left join [group] on user_to_group.group_id = [group].group_id

我尝试过使用组连接并加入DefaultIfEmpty,但我无法返回与SQL查询完全相同的结果。

谢谢。

@ChrisF,

当然,我可以把它分解成:

select user.username, user.email, user_items.item_number from user 
left join user_items on user.user_id = user_items.user_id 

我在linq2sql中有:

var users = (from u in db.users 
join ui in db.user_items on u.user_id equals ui.user_id into useritems from ui in useritems.DefaultIfEmpty() 
select new { user = u, item_number = useritems == null ? string.Empty : useritems.FirstOrDefault().item_number}); 

然而,它仍然没有返回它应该的所有结果,我无法看到我出错的地方。

3 个答案:

答案 0 :(得分:1)

您需要查看join ... into ...构造。

Here is an example on MSDN

......需要考虑的其他事项...... LINQ将允许您将简单的表结构转换为复杂的层次结构。左连接之外的另一个选项是嵌套查询。也许是这样的......

var selected = from user in users
               select new
               {
                   user,
                   items = from item in user_items
                           where item.user_id == user.user_id
                           join it in item_types
                               on item.item_type_id equals it.item_type_id
                           select it,
                   groups = from ug in user_to_groups
                            where ug.user_id == user.user_id
                            join @group in groups
                                on ug.group_id equals @group.group_id
                            select @group.name,
               };

答案 1 :(得分:1)

我发现了我的问题,我正在选择

useritems.FirstOrDefault().item_number

我选择的是(和FirstOrDefault!),而不是我用于加入的内容:

ui.item_number

所以我的完整linq查询是

var users = (from u in db.users
            join ug in db.user_to_groups on p.user_id equals pg.user_id into pgrp
            from ug in pgrp.DefaultIfEmpty()
            join g in db.groups on pg.group_id equals g.group_id into groups
            from g in groups.DefaultIfEmpty()
            join ui in db.user_items on u.user_id equals ui.user_id into useritems 
            from ui in useritems.DefaultIfEmpty()                          

        select new { user = u, item_number = ui == null ? string.Empty : ui.item_number, usergroup = g == null ? string.Empty : g.name});

感谢您的帮助!

答案 2 :(得分:0)

如果在对象之间定义一些关联,则可以更简洁地编写查询:

from u in db.Users
from ug in u.User_To_Groups.DefaultIfEmpty()
let g = ug.Group
from ui in u.UserItems.DefaultIfEmpty()
select new
{
  user = u,
  item_number = ui == null ? string.Empty : ui.item_number,
  usergroup = g == null ? string.Empty : g.name
});