【问题标题】:LINQ results matching ALL relationships匹配所有关系的 LINQ 结果
【发布时间】:2012-03-13 22:59:16
【问题描述】:

我的多对多关系如下:

产品表:

ProductID 
Description

产品特性表:

FeatureID 
ProductID 
FeatureValue

任何产品都可以有很多功能。 我有一个要素类

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 谢谢

【问题讨论】:

  • 向我们展示您尝试使用 Contains 的代码。这可能只是需要应用的一个小改动。

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


【解决方案1】:
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));
}

【讨论】:

  • 效果很好!谢谢!不太确定我是否理解为什么必须创建 featureId 和 featureValue 的新值。但如果你不按照你说的那样做,那肯定是行不通的。
猜你喜欢
  • 2010-12-04
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
相关资源
最近更新 更多