LINQ结果匹配所有关系

时间:2012-02-23 14:14:45

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

我有多对多的关系如下:

产品表:

ProductID 
Description

ProductFeatures表:

FeatureID 
ProductID 
FeatureValue

任何产品都可以有许多功能。 我有一个Feature类

public class Feature
{
    public Guid FeatureID { get; set; }
    public string FeatureValue { get; set; }
}

来自搜索的功能列表

List<Feature> searchFeaturesList = new List<Feature>();

foreach (string var in Request.QueryString)
{
    searchFeaturesList.Add(new Feature { FeatureID = new Guid(var.ToString()),   FeatureValue = Request.QueryString[var] });
}

如何使用LINQ to SQL获取与列表中的所有功能ID和功能值相匹配的所有产品的列表。 我尝试使用Contains,但我得到的所有产品都符合任何功能。我需要它来匹配所有功能。 请注意,每个FeatureID都可以具有不同的FeatureValue 谢谢

1 个答案:

答案 0 :(得分:2)

var query = Products.AsQueryable();

foreach (var feature in searchFeaturesList)
{
     // create here new values of featureId and featureValue otherwise will get the first ones from the iterator
     var featureId = feature.FeatureID;
     var featureValue = feature.FeatureValue;
     // each feature id and value is tested if exists in the ProductFeatures
     query = query.Where(p=>p.ProductFeatures
                             .Any(pf=> pf.FeatureID == featureId && pf.FeatureValue == featureValue));
}