I'm doing this with LINQ, but could possibly entertain creating a stored procedure for this. I have a working solution that retrieves both record lists and then filters with .Join()
in memory. I am looking for an improvement to this or a correction to my failed use of .Any()
so I don't need to load the full list of records for both first.
Situation:
I have two tables that are in different DBs (so no key/navigation prop relationships and I can't change this :/).
Table 1 is a list of Foos.
Foo Entity Properties: ID, ..., prop1, prop2, prop3, ...
Table 2 is a collection of Bars that match a unique combination of three properties found in a Foo. There is a unique key for (prop1, prop2, prop3). I didn't use a composite primary key since this is part of a web app and that would complicate navigation.
Bar Entity Properties: ID, prop1, prop2, prop3, ...
I need to retrieve all Bars that match a combo from the active Foos.
I've looked into potential solutions that use .Any() / .Exists(), but they have not worked.
//This doesn't work
var foos = db1.Foos.Where(d => d.IsActive)
.Select(c => new
{
c.prop1,
c.prop2,
c.prop3,
})
.ToList();
var fooBars = db2.Bars.Where(b => foos.Any(f => f == new { b.prop1,
b.prop2,
b.prop3 }))
.ToList();
My working solution: (see below as Answer)
I don't think that there is a way to combine this into one query since the entities are in different DbContexts, but is there a better way to retrieve filtered results without getting the entire list of bars first?