So I have this:
db.Table1
.Join(db.Table2, t1 => t1.id, t2 => t2.id, (t1, t2) => new { t1, t2 })
But what I need to do is join with an attribute value / key value table as well and for a specific attribute like:
SELECT * FROM Table1 t1
JOIN Table2 t2 ON t1.id = t2.id AND t2.attributeid = 123
How do I qualify that attributeid = 123 part?
A Where
clause should suffice:
db.Table1
.Join(db.Table2, t1 => t1.id, t2 => t2.id, (t1, t2) => new { t1, t2 })
.Where(x => x.t2.attributeId == 123);
Ideally Table1 should have a navigation property to Table2: (either HasOne or HasMany)
Singular Table2:
var result = db.Table1
.Include(x => x.Table2)
.Where(x => x.Table2.AttributeId == 123);
or for a collection of Table2s...
var result = db.Table1
.Include(x => x.Table2s)
.Where(x => x.Table2s.Any(t2 => t2.AttributeId == 123);
which would return any Table1 containing a Table2 with that attribute...
or with a collection that you want to filter the Table2s:
var result = db.Table1
.Where(x => x.Table2s.Any(t2 => t2.AttributeId == 123)
.Select(x => new
{
Table1 = x,
FilteredTable2s = x.Table2s.Where(t2 => t2.AttributeId == 123).ToList()
});
I think I'm going with Where. I was thinking maybe there was an equivalent of ON where it could pre-filter out before it gets to the where clause but maybe not (might even be the case that ON doesn't pre-filter down like I think it does).