Queryable.Join Method ef join

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查询

 

Queryable.Join Method

Definition

Correlates the elements of two sequences based on matching keys.

 

 

Join<TOuter,TInner,TKey,TResult>(IQueryable<TOuter>, IEnumerable<TInner>, Expression<Func<TOuter,TKey>>, Expression<Func<TInner,TKey>>, Expression<Func<TOuter,TInner,TResult>>)

 

Type Parameters

TOuter

The type of the elements of the first sequence.

TInner

The type of the elements of the second sequence.

TKey

The type of the keys returned by the key selector functions.

TResult

The type of the result elements.

Parameters

outer
IQueryable<TOuter>

The first sequence to join.

inner
IEnumerable<TInner>

The sequence to join to the first sequence.

outerKeySelector
Expression<Func<TOuter,TKey>>

A function to extract the join key from each element of the first sequence.

innerKeySelector
Expression<Func<TInner,TKey>>

A function to extract the join key from each element of the second sequence.

resultSelector
Expression<Func<TOuter,TInner,TResult>>

A function to create a result element from two matching elements.

Returns

IQueryable<TResult>

An IQueryable<T> that has elements of type TResult obtained by performing an inner join on two sequences.

 

 

Join返回的结果是IQueryable,后面跟where 的话,生成的sql是不带where的。

 

 

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-08-26 Async/Await FAQ (Stephen Toub)
2019-08-26 Async and Await (Stephen Cleary)
2019-08-26 Change Assembly Version in a compiled .NET assembly
2019-08-26 C# Under the Hood: async/await (Marko Papic)
2019-08-26 Bootstrap form-group and form-control
2015-08-26 在IIS中某一个网站启用net.tcp
2015-08-26 wcf 远程终结点已终止该序列 可靠会话出错
点击右上角即可分享
微信分享提示