Warm tip: This article is reproduced from serverfault.com, please click

Entity Framework join with a partially hardcoded "on" due to key value pair?

发布于 2020-11-30 22:19:15

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?

Questioner
Robert
Viewed
0
Steve Py 2020-12-01 06:51:10

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()
    });