Dav*_*ave 0 c# linq entity-framework-core
在我的Customer模型中,我有
public virtual ICollection<AddressModel> AddressIDs { get; set; }
Run Code Online (Sandbox Code Playgroud)
这些参考 AddressModel使我与客户及其地址之间存在一对多关系。
我有一个使用的搜索功能
var CustomerList = _context.Customers
.Where(ps => ps.Surname.Contains(surnameToSearchFor))
Run Code Online (Sandbox Code Playgroud)
以姓氏限制返回的数据集。
我正在尝试添加在地址中搜索邮政编码的功能。通过各种链接,这在Visual Studio中有效,但在执行时会中断
CustomerList = CustomerList
.Include(ps => ps.AddressIDs
.Where(a => a.Postcode == postcodeToSearchFor));
Run Code Online (Sandbox Code Playgroud)
与错误
InvalidOperationException: The property expression 'ps => {from AddressModel a in ps.AddressIDs where ([a].Postcode == __p_0) select [a]}' is not valid. The expression should represent a property access: 't => t.MyProperty
Run Code Online (Sandbox Code Playgroud)
如何Where在子表的LINQ中添加子句?
编辑 对于在Linq中建议使用Multiple WHERE子句作为答案的人,该问题显然与单个表有关,而我明确询问了子表。
您不能在Include中使用where语句。您可以通过单个linq查询获得所需的内容,如下所示:
var CustomerList = _context.Customers.Where(ps =>
ps.Surname.Contains(surnameToSearchFor)
&& ps.AddressIDs.Any(ad => ad.Postcode == postcodeToSearchFor ));
Run Code Online (Sandbox Code Playgroud)