Linq多重连接(如果存在)

时间:2012-09-18 15:57:23

标签: c# linq entity-framework

我正在努力实现这段代码。如果有人帮忙,将非常感激。

var result = (from fv in db.UsFavourites.Where(m => m.UserID == currentUserId)
                      join ad in db.CtArticleDetails.Where(m => m.ArticleStatusId == ConfigHelper.Published) on fv.ArticleReferenceID equals ad.ArticleReference
                      join pcs in db.PcPages.Where(m => m.Status == ConfigHelper.Published) on fv.PageReferenceID equals pcs.Reference
                      join prd in db.PrProducts.Where(m => m.ProductStatusID == ConfigHelper.Published) on fv.ProductReferenceID equals prd.ProductReference
                      select new FavouriteModel
                      {
                          FavouriteId = fv.FavouriteID,
                          Title = ad.Title ?? pcs.PageName ?? prd.Name,
                          Url = ad.Title ?? pcs.PageName ?? prd.Name,
                          ArticleReferenceID = (int)fv.ArticleReferenceID,
                          PageReferenceID = (int)fv.PageReferenceID,
                          ProductReferenceID = (int)fv.ProductReferenceID
                      });

基本上,我正在尝试加入3个表格,如你所见:ad,pcs,prd。如果Pcs不存在,代码应该忽略。有人可以建议吗?

添加了数据库设计以明确: enter image description here

1 个答案:

答案 0 :(得分:1)

我认为你打算在

上做左联
  • pcs db.PcPages

  • ad db.CtArticleDetails

DefaultIfEmpty用于使其成为左连接

var result = (from fv in db.UsFavourites.Where(m => m.UserID == currentUserId)
                      from ad in db.CtArticleDetails.Where(m => m.ArticleStatusId == ConfigHelper.Published) 
                                                    .Where(m => fv.ArticleReferenceID == m.ArticleReference)
                                                    .DefaultIfEmpty()
                      from pcs in db.PcPages.Where(m => m.Status == ConfigHelper.Published)
                                            .Where(m => fv.PageReferenceID == m.Reference)
                                            .DefaultIfEmpty()
                      join prd in db.PrProducts.Where(m => m.ProductStatusID == ConfigHelper.Published) on fv.ProductReferenceID equals prd.ProductReference
                      select new FavouriteModel
                      {
                          FavouriteId = fv.FavouriteID,
                          Title = ad.Title ?? pcs.PageName ?? prd.Name,
                          Url = ad.Title ?? pcs.PageName ?? prd.Name,
                          ArticleReferenceID = (int)fv.ArticleReferenceID,
                          PageReferenceID = (int)fv.PageReferenceID,
                          ProductReferenceID = (int)fv.ProductReferenceID
                      });