有没有更好的方法来编写这样的linq2sql组代码?与T-SQL版本相比似乎太长了,似乎它会在性能方面遇到麻烦。
var Result = (
// [ 1. JOIN
from l in db.Lists
where l.ProfileID == ID
join item in db.Items on l.ID equals item.ListID into ListItem
//orderby l.CreateDate descending
// ]
// [ 2. JOIN - 1. GROUPBY
from l_item in ListItem.DefaultIfEmpty() // left join için
group l_item by new {
l.CategoryID,
l.CreateDate,
l.Header,
Min_ItemListID = ListItem.Min(c=>c.ListID)
} into G_List
join i_photo in db.ItemPhotos on G_List.Key.Min_ItemListID equals i_photo.ItemID into ListItem2
// ]
// [ 2. GROUPBY
from ll_item in ListItem2.DefaultIfEmpty()
group ll_item by new {
G_List.Key.CategoryID,
G_List.Key.CreateDate,
G_List.Key.Header,
G_List.Key.Min_ItemListID,
Min_ItemPhoto_FileName = ListItem2.Min(c=>c.FileName)
} into GG_List
// ]
select new TList.General_ListViewModel
{
CategoryID = GG_List.Key.CategoryID,
CreateDate = GG_List.Key.CreateDate,
Header = GG_List.Key.Header,
FirstImageURL = GG_List.Key.Min_ItemPhoto_FileName
}
);
答案 0 :(得分:3)
我认为你不需要外连接部分,你已经使用组连接分组了所有内容(通过join ... into
)。我相信你可以将这个问题简化为:
var query =
from list in db.Lists
where list.ProfileID == ID
join item in db.Items on list.ID equals item.ListID into listItems
//orderby list.CreateDate descending
join photo in db.ItemPhotos
on listItems.Min(c=>c.ListID) equals photo.ItemID into listPhotos
select new TList.General_ListViewModel
{
CategoryID = list.CategoryID,
CreateDate = list.CreateDate,
Header = list.Header,
FirstImageURL = listPhotos.Min(c=>c.FileName),
};