简体   繁体   English

如何在实体框架中查询与ID数组的多对多关系

[英]How to query a many to many relationship with an array of ID's in Entity Framework

Say there are stores, customers, and credit accounts. 假设有商店,客户和信用帐户。 So customers and stores have a many-to-many relationship through the credit account table. 因此,客户和商店通过信用帐户表具有多对多关系。

If I want every customer that has an account at a given store, I could access it like follows. 如果我希望每个在给定商店中拥有帐户的客户都可以按以下方式访问它。

var customers = dbContext.Customers
    .Where(c => c.CreditAccounts.Select(a => a.StoreID).Contains(storeID));

That seems to work but when I want to search by multiple storeIds, I get an empty result set. 这似乎可行,但是当我想通过多个storeId搜索时,我得到一个空结果集。 Here are some things I've tried. 这是我尝试过的一些方法。

var customers = dbContext.Customers
    .Where(c => c.CreditAccounts.Any(a => storeIDs.Contains(a.StoreID)));

And

var customers = dbContext.Customers
    .Where(c => c.CreditAccounts.Select(a => a.StoreID).Intersect(storeIDs).Count() > 0);

These always give me empty results. 这些总是给我空洞的结果。 How can I achieve this without writing a raw SQL query? 如何在不编写原始SQL查询的情况下实现这一目标?

Update 更新

I did not have the data that I thought I had. 我没有我认为的数据。 Once that was corrected, my queries began to work. 更正后,我的查询开始起作用。 I think the question is still valid though because it's not clear whether any of these perform well, so other users might wish to respond with the most efficient way to retrieve the results. 我认为这个问题仍然有效,因为尚不清楚这些方法是否能很好地执行,因此其他用户可能希望以最有效的方式来检索结果。

The following linq query will return the results that you are looking for - however, I am not certain that it will perform well at all: 以下linq查询将返回您要查找的结果-但是,我不确定它的性能是否会很好:

var results = dbContext.Customers
    .Where(c => c.CreditAccounts.Join(storeIds.ToList(), a => a.StoreId, s => s, (a,s)=>s).Any());

You may get better performance by finding the credit accounts that intersect with the StoreID, and then joining the list of credit accounts with the customers table - although I can't tell from the code you have provided whether you have direct access to a list of creditaccounts. 通过找到与StoreID相交的贷方帐户,然后将贷方帐户列表与客户表结合起来,可能会获得更好的性能-尽管我无法从您提供的代码中得知您是否可以直接访问以下代码: creditaccounts。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM