帮助实体查询

时间:2010-11-06 06:47:14

标签: asp.net vb.net entity-framework linq-to-entities entity-framework-4

我似乎无法弄清楚如何正确编写此查询。我尝试了各种组合,但没有任何工作。

以下是我的数据库模型的相关部分: alt text

我需要选择与给定类别和组匹配的产品,并匹配给定的Year,Make,Model,submodel。我在下面做了这个:

 ItemList = From P In gDataContext.Products.Include("Groups").Include("Groups.Category1").Include("LookupYearMakeModels") From G In P.Groups Where G.Category = Cat And G.Grp = Group  From Y In P.LookupYearMakeModels Where Y.Year = YMM.Year And Y.Make = YMM.Make And Y.Model = YMM.Model And Y.Submodel = YMM.Submodel Select P

我现在还必须选择与Category和Group匹配的产品,但是Universal(Product.Univeral = True)。

我目前正在撰写两个查询,上面的一个和下面的一个。我只是简单地使用ItemList.AddRange(ItemList2)来合并两者的结果

ItemList2 = From P In gDataContext.Products.Include("Groups").Include("Groups.Category1") where P.Universal From G In P.Groups Where G.Category = Cat And G.Grp = Group  Select P

但我希望将两个查询合并为一个并避免合并结果。我该怎么办?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

我试图建立一个类似的模型,我相信这是有效的。在这里,我选择的产品具有与给定类别和组匹配的组,并且具有匹配的年份/品牌/型号/子模型是通用的。

ItemList = From P In gDataContext.Products.Include("Groups").Include("Groups.Category1").Include("LookupYearMakeModels") 
           Where P.Groups.Any(Function(G) G.Category = Cat And G.Grp = Group) _
                And ( _
                        P.LookupYearMakeModels.Any(Function(Y) Y.Year = YMM.Year And Y.Make = YMM.Make And Y.Model = YMM.Model And Y.Submodel = YMM.Submodel) _
                        Or _
                        P.Universal = True _
                    )
           Select P

HTH

答案 1 :(得分:0)

您可以使用IQueryable.Union Method:

ItemList = (From P In gDataContext.Products                                 
                                  .Include("Groups.Category1")
                                  .Include("LookupYearMakeModels") 
            From G In P.Groups 
                Where G.Category = Cat And G.Grp = Group  
            From Y In P.LookupYearMakeModels 
                Where Y.Year = YMM.Year 
                     And Y.Make = YMM.Make And Y.Model = YMM.Model 
                     And Y.Submodel = YMM.Submodel 
            Select P)
            .Union(
            From P In gDataContext.Products                     
                                  .Include("Groups.Category1")
            Where P.Universal
            From G In P.Groups Where G.Category = Cat And G.Grp = Group
            Select P)
相关问题