Search code examples
c#entity-frameworkfluent

Joining Tables Using Entity Framerwork Fluent Syntax


I have tables Table1, Table2, Table3 and so on. To handle auditing, I use Audit table with the following fields Id, Username, ChangeTime, ChangeType, TableName and TableRecordId.

To obtain all records in Table1 joined with Audit on Table1.Id = Audit.TableRecordId where Username is "jdoe" for example, I have the following:

var results = db.Table1s
            .Join(db.Audits.Where(a => a.Username == "jdoe"),
            t => t.Id,
            a => a.RecordId,
            (t, a) => new { Table1 = t, Audit = a });

But when I run it I get the following error:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType1`2[SampleApp.Models.Table1,AuditLibraryContext.Models.Audit]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[AuditTrackerSample.Models.Table1]'.

Got it working I ended up with the following code:

var results = db.Table1s
            .Join(db.Audits.Where(a => a.Username == "jdoe"),
            t => t.Id,
            a => a.RecordId,
            (t, a) => t);

Solution

  • Please do a thorough search before asking a general duplicate question.

    var results = db.Table1s
                  .Join(db.Audits.Where(a => a.Username == "jdoe"),
                  t => t.Id,
                  a => a.TableRecordId,
                  (t, a) => new { Table1 = t, Audit = a });
    
    var results = from t in db.Table1s
                  join a in db.Audits
                  on t.Id equals a.TableRecordId
                  where a.Username == "jdoe"
                  select new { Table1 = t, Audit = a};
    

    Reference