entity frameworkjoin3个表
我想join三张桌子,但是我不明白这个方法…
我完成了连接2个表格
var entryPoint = dbContext.tbl_EntryPoint .Join(dbContext.tbl_Entry, c => c.EID, cm => cm.EID, (c, cm) => new { UID = cm.OwnerUID, TID = cm.TID, EID = c.EID, }). Where(a => a.UID == user.UID).Take(10);
我想用TID PK包含tbl_Title表并获得Title字段。
非常感谢
我认为使用基于语法的查询会更容易:
var entryPoint = (from ep in dbContext.tbl_EntryPoint join e in dbContext.tbl_Entry on ep.EID equals e.EID join t in dbContext.tbl_Title on e.TID equals t.TID where e.OwnerID == user.UID select new { UID = e.OwnerID, TID = e.TID, Title = t.Title, EID = e.EID }).Take(10);
您应该添加orderby
子句,以确保Top(10)
返回正确的前十个项目。
这是未经testing的,但我相信这个语法应该适用于lambda查询。 当你用这个语法连接更多的表时,你必须深入到新的对象中去达到你想要处理的值。
var fullEntries = dbContext.tbl_EntryPoint .Join( dbContext.tbl_Entry, entryPoint => entryPoint.EID, entry => entry.EID, (entryPoint, entry) => new { entryPoint, entry } ) .Join( dbContext.tbl_Title, combinedEntry => combinedEntry.entry.TID, title => title.TID, (combinedEntry, title) => new { UID = combinedEntry.entry.OwnerUID, TID = combinedEntry.entry.TID, EID = combinedEntry.entryPoint.EID, Title = title.Title } ) .Where(fullEntry => fullEntry.UID == user.UID) .Take(10);
var entryPoint = (from ep in dbContext.tbl_EntryPoint join e in dbContext.tbl_Entry on ep.EID equals e.EID join t in dbContext.tbl_Title on e.TID equals t.TID where e.OwnerID == user.UID select new { UID = e.OwnerID, TID = e.TID, Title = t.Title, EID = e.EID }).Take(10); Great answer