Search code examples
c#linqfluentef-fluent-api

Fluent API C# querying across entities


I have two tables, both have primary keys defined, with a foreign key between the two.

    Table 1         Table 2

PK  ID           PK ID   
                 FK Table1ID.ID 
    Name            DescriptionId
                    Description

What I am trying to do is recover all of Table1,by ID, but just a small subset of Table2.

This recovers all records from Table2 for ID 300.

var option = unitOfWork.Repository<Table1>()
                       .Query(x => x.ID == 300 )
                       .Include(y => y.Table2)
                       .Select()
                       .FirstOrDefault();

I have modified the above as follows:

.Query(x => x.ID == 300 && x.Table2.Where(w => w.DescriptionId == 2))

and

.Include(y => y.Table2.Where(w => w.DescriptionId == 2))

neither of these work.


Solution

  • You will need to do something similar to the below.

    var option = unitOfWork.Repository<Table1>()
                           .Query(x => x.ID == 300 )
                           .Include(y => y.Table2)
                           .Select(z => new{Field1 = x.Field1, Field2 = x.Field2, Field3 = y.Field1})
                           .FirstOrDefault();