简体   繁体   中英

EF6 IN clause on specific properties

Good morning,

I'm having trouble with a EF query. This is what i am trying to do.

First i am pulling a list of ID's like so (List of IDs are found in the included x.MappingAccts entity):

Entities.DB1.Mapping mapping = null;
using (var db = new Entities.DB1.DB1Conn())
{
    mapping = db.Mappings.Where(x => x.Code == code).Include(x => x.MappingAccts).FirstOrDefault();
}

Later, i'm trying to do a query on a different DB against the list of Id's i pulled above (essentially a IN clause):

using (var db = new Entities.DB2.DB2Conn())
{
    var accounts = db.Accounts.Where(mapping.MappingAccts.Any(y => y.Id == ?????????)).ToList();
}

As you can see i only got part way with this.

Basically what i need to do is query the Accounts table against it's ID column and pull all records that match mapping.MappingAccts.Id column.

Most of the examples i am finding explain nicely how to do this against a single dimension array but i'm looking to compare specific columns.

Any assist would be awesome.

Nugs

An IN clause is generated using a IEnumberable.Contains

From the first DB1 context, materialize the list of Id's

var idList = mapping.MappingAccts.Select(m => m.Id).ToList();

Then in the second context query against the materialized list of id's

var accounts = db.Accounts.Where(a => idList.Contains(a.Id)).ToList();

The only problem you may have is with the amount of id's you are getting in the first list. You may hit a limit with the sql query.

This will give the list of Accounts which have the Ids contained by MappingAccts

using (var db = new Entities.DB2.DB2Conn())
{
    var accounts = db.Accounts.Where(s => mapping.MappingAccts.Any(y => y.Id == s.Id)).ToList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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