开发者

LINQ to SQL join tables special blend

开发者 https://www.devze.com 2023-02-17 05:10 出处:网络
I\'m trying to get data from two tables. Todo_Lists and Todo_Items. I manged to join the two like this:

I'm trying to get data from two tables. Todo_Lists and Todo_Items. I manged to join the two like this:

from list in dataContext.Todo_Lists
from item in dataContext.Todo_List_Items
where list.UserID == userID && list.List开发者_JAVA百科ID == item.ListID
select new
{
    ListID = list.ListID,
    ListName = list.ListName, 
    ItemID = item.ItemID, 
    ItemName = item.ItemName 
};

That's all good in the hood if I just want the lists with Items on them. But I need to return all the lists and where there are Items I need them to be joined in.

Thankfull for any information.


from Lists in dataContext.Todo_Lists
where Lists.UserID == userID
select new
{
    ListID = Lists.ListID,
    ListName = Lists.ListName, 
    Items = dataContext.Todo_List_Items
                           .Where(i => Lists.ListID == i.ListId)
                           .Select(new {
                                            ItemID = Items.ItemID, 
                                            ItemName = Items.ItemName 
                                       }
};

That will give you null if there isn't anything in the Items


sounds like a left outer join: (untested)

from list in dataContext.Todo_Lists
where list.UserID == userID
join itemTemp in dataContext.Todo_List_Items on list.ListID equals item.ListID into itemGroup
from item in itemGroup.DefaultIfEmpty()

select new
{
    ListID = list.ListID,
    ListName = list.ListName, 
    ItemID = item == null? null : item.ItemID, 
    ItemName = item == null? null : item.ItemName 
};

you'll probably need to cast the nulls for the conditional to work - I left it out cos I don't know the type. See here for more info on left outer joins using linq.

0

精彩评论

暂无评论...
验证码 换一张
取 消