Linq到Sql子实体多个和运算符

时间:2012-03-30 16:42:03

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

嗨我有一个FeatureSet Id数组,My Vehicles表有子表作为FeatureSets 我编写了Sql Query Like

    SELECT [t0].[ID] 
FROM [dbo].[SearchResultView] AS [t0]
 Join [dbo].[VehicleFeatureSet] AS [t1] on t0.ID = t1.VehicleID
where t1.FeatureSetID = 1 and t1.FeatureSetID= 2 and t1.FeatureSetID= 3 

我试过了。但我不能

var features = Request.QueryString["FeatureSets"].Split(',').ToList().ConvertAll(new Converter<string, int>(StrinToint)); 
IQueryable<SearchResultView> result = db.SearchResultViews.Where(m => m.Active == true);


            foreach (var featuree in features)
            {
                result = result.Where(m => m.VehicleFeatureSets.Any(c => c.FeatureSetID == featuree));
            }

如何编写此LINQ查询

2 个答案:

答案 0 :(得分:1)

这样的东西?虽然你想在FeatureSetId上匹配1,2和3?我按照原样保留了它,但是如果那是你的意思,它们可以改为OR(||)吗?

 var results = (from r in db.SearchResultViews
              join v in db.VehicleFeatureSet 
                 on r.ID equals v.VehicleID
              where r.Active 
                  && v.FeatureSetID == 1
                  && v.FeatureSetID == 2 
                  && v.FeatureSetID == 3
              select r.ID)
               .ToList();

编辑:好的,我现在所做的只是重写你的foreach声明,你可以用以下内容替换它:

results = features
    .Aggregate(results, (current, feature) => current
        .Where(v => v.VehicleFeatureSets
            .Any(vf => vf.VehicleFeatureSetId == feature))
        .ToList());

答案 1 :(得分:1)

我将My LInq Query转换为Sql Query。 实际上,我无法为此编写LINQ查询:)

 SELECT  Vehicle.[ID]
      ,[Make]
      ,[Model]
      ,[Km]
      ,[RegistrationYear]
      ,[Price]
      ,[Currency]
      ,[AdsStartDate]
      ,[ThumbPhoto]
  FROM [SearchResultView] as Vehicle 
 left Join VehicleFeatureSet vs on Vehicle.ID=vs.VehicleID where Vehicle.Active = 1
 AND vs.FeatureSetID IN( 1,5,7,9)  //  1,5,7,9 comes from array
group by Vehicle.[ID],[Make]
      ,[Model]
      ,[Km]
      ,[RegistrationYear]
      ,[Price]
      ,[Currency]
      ,[AdsStartDate]
      ,[ThumbPhoto]
Having Count(vs.FeatureSetID) = 4 // length of my feature array
// sb = msSql query ,StringBuilder
// Then I used DataContext.ExecuteQuery()
db.ExecuteQuery<SearchResultView>(sb.ToString());

问题已解决,感谢您提供帮助。