Skip to main content
 首页 » 编程设计

c#之Linq之在实体或子实体中搜索字符串

2024年02月05日22www_RR

我有 Suppliers 和 Items 实体,其中 Suppliers 与 Items 具有一对多关系。

我需要在两者中搜索一个字符串,这样搜索结果将返回以下内容:

  1. 名称中包含搜索字符串的所有供应商及其所有项目。
  2. 拥有名称包含搜索字符串的项目的所有供应商。

到目前为止,我一直在用两个列表做这件事,然后做一个联合:

var suppliers = repository.Suppliers.Where 
       (s => s.Name.Contains(searchString)).Include(Items); 
 
var itemSuppliers = repository.Suppliers.Include(Items).Where 
                (s => s.Items.Any(i => i.Name.Contains(searchString)); 

有没有更好的方法,最好是一次查询?

谢谢

请您参考如下方法:

repository.Suppliers.Include(Items).Where(s => s.Name.Contains(searchString) || s.Items.Any(item => item.name.Contains(searchString))); 

希望对你有帮助。