使用Entity Framework Fluent语法连接表

时间:2014-05-16 18:53:34

标签: c# entity-framework fluent

我有Table1,Table2,Table3等表。为了处理审计,我使用Audit表,其中包含以下字段Id,Username,ChangeTime,ChangeType,TableName和TableRecordId。

要获取Table1中与Audit1.Id = Audit.TableRecordId连接的所有记录,其中Username为“jdoe”,例如,我有以下内容:

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

但是当我运行它时,我收到以下错误:

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]'.

让它工作我最终得到了以下代码:

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

1 个答案:

答案 0 :(得分:2)

在询问一般性重复问题之前,请先进行全面搜索。

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