帮助我使用实体框架从 SQL 转换为 linq 嵌套 lambda 表达式
Posted
技术标签:
【中文标题】帮助我使用实体框架从 SQL 转换为 linq 嵌套 lambda 表达式【英文标题】:Helpme to Convert from SQL to linq Nested lambda Expression with EntityFramework 【发布时间】:2013-01-15 21:05:14 【问题描述】:我正在尝试从 SQL 中获取一些数据,但我无法使用 Linq 来完成,在 T-SQL 中这项工作:
select *
from MTRBatch MB
Inner Join MTR M on MB.Id = M.MTRBatchId
Inner JOIN MTRHeats MH on M.Id = MH.MTRId
LEFT OUTER JOIN Vendor V on MB.VendorId = v.Id
Inner Join Manufacturer MF on MB.ManufacturerId = MF.Id
Where MB.ManufacturerId = 1
AND MH.Heat = 'z01'
我需要除了那个过滤器之外的所有树。
我试过了,但没用:
MTRBatches
.Include(x => x.MTRs.Select(m => m.MTRHeats))
.Include(x => x.Manufacturer)
.Include(x => x.Vendor)
.Where(x => (x.Manufacturer.Id == 1));
.Where(x => x.MTRs.Any(m => m.MTRHeats.Any(h => h.Heat == 'z01')));
【问题讨论】:
没有像...那样工作?结果错误?碰撞燃烧?没有编译? 结果不正确:它给我带来了所有 MTR,就像 MH.HEat 过滤器没有发生 【参考方案1】:这应该会有所帮助; dataContext
是您的 Entity Framework container
实例的名称。
var result = dataContext.MTRBatches
.Join(dataContext.MTRs,
mb => mb.Id,
mtr => mtr.MTRBatchId,
(mb, mtr) => new Batch = mb, MTR = mtr )
.Join(dataContext.MTRHeats,
x => x.MTR.Id,
mh => mh.MTRId,
(x, mh) => new Batch = x.Batch, MTR = x.MTR, Heat = mh )
.Join(dataContext.Vendors.DefaultIfEmpty(),
x => x.Batch.VendorId,
v => v.Id,
(x, v) => new Batch = x.Batch, MTR = x.MTR, Heat = x.Heat, Vendor = v )
.Join(dataContext.Manufacturers,
x => x.Batch.ManufacturerId,
mf => mf.Id,
(x, mf) => new Batch = x.Batch, MTR = x.MTR, Heat = x.Heat, Vendor = x.Vendor, Manufacturer = mf)
.Where(x => x.Manufacturer.Id == 1 && x.Heat.Heat == "z01");
【讨论】:
以上是关于帮助我使用实体框架从 SQL 转换为 linq 嵌套 lambda 表达式的主要内容,如果未能解决你的问题,请参考以下文章
使用 LINQ 和实体框架在一个 SQL 查询中从多个表中提取数据