[英]lambda expression to query a collection by a collection
I want to create a lambda expression to query a collection by a collection 我想创建一个lambda表达式来按集合查询集合
In a EF code first environment, I have the following data objects 在EF代码优先环境中,我有以下数据对象
I have a class named price 我有一个名为price的课程
public class Price
{
public int Id { get; set; }
public string DisplayName { get; set; }
public double Amount { get; set; }
public bool IsActive { get; set; }
public int ItemId { get; set; }
[ForeignKey("ItemId")]
public virtual Item Item { get; set; }
public ICollection<PriceOption> PriceOptions { get; set; }
}
And a related class named 还有一个名为的相关类
public class PriceOption
{
public int Id { get; set; }
public int PriceId { get; set; }
[ForeignKey("PriceId")]
public virtual Price Price { get; set; }
public int OptionId { get; set; }
[ForeignKey("OptionId")]
public virtual Option Option { get; set; }
}
I have two search criteria 我有两个搜索条件
int ItemId
List<int> optionIds
I want to create a lambda expression to select all prices that are equil to the ItemId (easy) and where the PriceOptions collection contains all of the optionIds. 我想创建一个lambda表达式来选择所有与ItemId(easy)相等的价格,以及PriceOptions集合包含所有optionIds的价格。
The Idea is something like this but of course this it just to show what I am trying to achive. 想法是这样的,但当然这只是为了表明我想要实现的目标。
List<Price> prices = _priceRepository.FindAll().Where(x => x.ItemId == item.Id && x.PriceOptions.All(y => y.OptionId == optionIds)).ToList();
Thank you for your help 谢谢您的帮助
Earl 伯爵
The following LINQ query based on Contains
and Count
methods produces a simpler (thus eventually faster) SQL query: 以下基于
Contains
和Count
方法的LINQ查询生成一个更简单(因此最终更快)的SQL查询:
var matchCount = optionIds.Count;
var prices = _priceRepository.FindAll()
.Where(p => p.ItemId == ItemId &&
p.PriceOptions.Count(po => optionIds.Contains(po.OptionId)) == matchCount)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.