EF join

两张表:

var query = db.Categories         // 第一张表
   .Join(db.CategoryMaps,         // 第二张表
      c => c.CategoryId,          // 主键
      cm => cm.ChildCategoryId,   // 外键
      (c, cm) => new { Category = c, CategoryMap = cm }) // 关联后的结果对象集
   .Select(x => x.Category);  // select 查询结果集

多张表:

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)
    .OrderBy(p=>p.UID)
    .Take(10);

优点:coding方便

缺点:join多张表的情景,代码冗长

替代方法:创建数据库视图,对视图进行EF查询

posted @ 2019-07-02 10:49  leco_lin  阅读(324)  评论(0编辑  收藏  举报