[英]Two lambda expressions in a single query
I have a list of products and I have included ProductMetadatas in the query like this: 我有一个产品列表,并且在查询中包括了ProductMetadatas,如下所示:
var products = _dbContext.Set<Product>()Include(x=>x.Productmetadatas).
Where(x => x.CompanyId == LoggedInUser.CompanyId && x.Active).ToList();
Now, what I want to do is I want to filter the ProductMetadats according to the CompanyId, like 现在,我要做的就是根据CompanyId过滤ProductMetadats,例如
var products = _dbContext.Set<Product>()Include(x=>x.Productmetadatas).
Where(x => x.CompanyId == LoggedInUser.CompanyId && x.Active &&
x.ProductMetadatas.Where(pm => pm.CompanyId == LoggedInUser.CompanyId)).ToList();
How can I do it in a single query? 如何在单个查询中完成?
If you want all products that actually do match your current users companyId you have to change it to the following: 如果要使所有产品确实与当前用户的companyId匹配,则必须将其更改为以下内容:
var products = _dbContext.Set<Product>()Include(x=>x.Productmetadatas).
Where(x => x.CompanyId == LoggedInUser.CompanyId && x.Active &&
x.ProductMetadatas.Any(pm => pm.CompanyId == LoggedInUser.CompanyId)).ToList();
As you can guess .Any() checks if any element in your list matches your LINQ expression and returns a boolean. 您可以猜到.Any()检查列表中的任何元素是否与LINQ表达式匹配并返回布尔值。 With that your expression is valid.
这样,您的表情就有效了。
Previously it could not work because .Where() returns a list of elements. 以前它无法工作,因为.Where()返回元素列表。
EDIT: 编辑:
Alright as it was noted that you want to adjust the ProductMetdatas you can do the following: 就像已经指出的那样,您要调整ProductMetdatas可以执行以下操作:
Create an extension for IEnumerable<T>
: 创建
IEnumerable<T>
的扩展名:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach(T item in source)
action(item);
}
And then adjust your LINQ like this: 然后像这样调整您的LINQ:
var products = _dbContext.Set<Product>()Include(x=>x.Productmetadatas).
Where(x => x.CompanyId == LoggedInUser.CompanyId && x.Active).
ForEach(x => x.ProductMetadatas = x.ProductMetadatas.
Where(pm => pm.CompanyId == LoggedInUser.CompanyId).ToList()).ToList();
Now you invoke a function on each element which filters the ProductMetadatas and sets the property of your product to the filtered ProductMetadatas. 现在,您在每个元素上调用一个函数来过滤ProductMetadatas并将产品的属性设置为过滤后的ProductMetadatas。
You can use join to filter. 您可以使用join进行过滤。
var result = (from tbl in _dbContext.Set<Product>()
join lst in ProductMetadatas on lst.CompanyID eqauls LogginInUSer.CompanyID
where tbl.CompanyId == LoggedInUser.CompanyId && tbl.Active
select tbl)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.