--TabA
create table TabA
(
Id int identity(1,1) primary key,
Name nvarchar(20)
)
--TabB
create table TabB
(
Id int identity(1,1) primary key,
Name nvarchar(20),
Aid int references TabA(Id)
)
--TabC
create table TabC
(
Id int identity(1,1) primary key,
Name nvarchar(20),
Bid int references TabB(Id)
)参照两表Join语句,使用方法语法可以这么写:
var data = context.TabAs.Join(context.TabBs, taba => taba.Id, tabb => tabb.Aid, (taba, tabb) => new { AName = taba.Name, BName = tabb.Name, Bid = tabb.Id }).Join(context.TabCs, item => item.Bid, tabc => tabc.Bid, (item, tabc) => new { AName = item.AName, BName = item.BName, CName = tabc.Name });这样虽可以达到要求,但每Join一张表,new中字段就得重复写一次,若返回字段多,书写麻烦,语句也非常长,经过测试,最终优化如下:
var data = context.TabAs.Join(context.TabBs, taba => taba.Id, tabb => tabb.Aid, (taba, tabb) => new { taba, tabb }).Join(context.TabCs, item => item.tabb.Id, tabc => tabc.Bid, (item, tabc) => new { AName = item.taba.Name, BName = item.tabb.Name, CName = tabc.Name });当然了,也可以用Linq查询语法来实现,那就简单多了:
var data = from taba in context.TabAs
join tabb in context.TabBs on taba.Id equals tabb.Aid
join tabc in context.TabCs on tabb.Id equals tabc.Bid
select new { AName = taba.Name, BName = tabb.Name, CName = tabc.Name };
评论(0)
暂无评论。