C# LINQ 过滤子表中的记录

C# LINQ Filter records in child tables

我有一个主要的table“SALES”和两个次要的tables“PRODUCTS”和“SERVICES”,我需要select只有“SALES”中的记录包含用户输入的一些产品或服务,我不需要带销售记录和产品,只是过滤。首先,我按销售日期在 table“SALES”中制作过滤器:

var query = (from p in _contexto.sales
where p.datesale.Value.Date >= Convert.ToDateTime(strDtI).Date &&
p.datesale.Value.Date <= Convert.ToDateTime(strDtF).Date
select p);

现在假设用户还想用字符串数组中的词过滤具有产品或服务的销售

words = ['apple', 'beef', 'cleaning', 'haircut']

如果你收到单词数组,我尝试了下面的过滤器,但它没有用,它一直带来所有记录。

var queryi = (from i in _contexto.products
where words.Contains(i.name) || words.Contains(i.description) select i);
//var queryj = (from i in _contexto.services
//where words.Contains(i.name) || words.Contains(i.description) select i);

//query = query.Where(p => queryi.All(c => c.idsale != p.id) || queryj.All(c => c.idsale != p.id));
query = query.Where(p => queryi.All(c => c.idsale != p.id));

我哪里失败了,是否有更好、更高效的方法来做到这一点? 谢谢!

使用更具描述性的变量名称,并假设您只想查找名称或描述与 words 之一完全相同的产品,您将:

var salesInPeriod = from s in _contexto.sales
                    where Convert.ToDateTime(strDtI).Date <= s.datesale.Value.Date &&
                          s.datesale.Value.Date <= Convert.ToDateTime(strDtF).Date
                    select s;

var matchingidsales = from p in _contexto.products
                      where words.Contains(p.name) || words.Contains(p.description)
                      select p.idsale;

var ans = from s in salesInPeriod
          where matchingidsales.Contains(s.id)
          select s;

PS:我颠倒了日期比较,因为我认为这样更容易看出你在做一个测试。