连接后,Linq到sql是不同的

本文关键字:sql 是不同 Linq 连接 | 更新日期: 2023-09-27 18:05:20

我有一个连接查询,我想通过使用distinct来过滤这个查询的结果。我只想买一双相同品牌、型号、原色和副色的鞋。我该怎么做呢?这是我的join查询。

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
            };

连接后,Linq到sql是不同的

我找到了解决方案。这个查询做了我想做的事情

            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};

从输出中删除price,并像这样使用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();