Linq to sql加入后区别

时间:2014-05-27 17:37:53

标签: c# asp.net sql sql-server linq

我有一个连接查询,我想通过使用distinct来过滤此查询的结果。我想只得到一个具有相同品牌,型号,原色和二次色的鞋子。我该怎么做?这是我的加入查询。

var query = from b in db.BrandTbls.AsQueryable()
            join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
            join s in db.ShoeTbls on m.ModelID equals s.ModelID
            join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
            where s.Quantity > 0
            orderby m.ModelName
            select new 
            { 
                s.ShoeID, 
                m.ModelName, 
                m.Price, 
                b.BrandName, 
                i.ImagePath
            };

2 个答案:

答案 0 :(得分:2)

我找到了解决方案。此查询大致完成了我想要做的事情

            var query = from b in db.BrandTbls.AsQueryable()
                    join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
                    join s in db.ShoeTbls on m.ModelID equals s.ModelID
                    join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
                    group new {b,m,s,i} by new {b.BrandName,m.ModelName,m.Price,s.ShoeID,s.PrimaryColor,s.SecondaryColor,i.ImagePath} into g
                    select new {g.Key.ShoeID,g.Key.BrandName,g.Key.ModelName,g.Key.ImagePath,g.Key.Price};

答案 1 :(得分:0)

从输出中删除价格并使用Distinct(),如下所示:

var query = (from b in db.BrandTbls.AsQueryable()
            join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
            join s in db.ShoeTbls on m.ModelID equals s.ModelID
            join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
            where s.Quantity > 0
            orderby m.ModelName
            select new 
            { 
                s.ShoeID, 
                m.ModelName, 
                b.BrandName, 
                i.ImagePath
            }).Distinct();