c# - 如何在实体框架中使用 lambda 表达式进行此查询?
问题描述
这是我的 SQL 查询:
select
m.Name, s.Time, t.TheaterNumber
from
Movies m
join
MovieSeanceTheaters mst on mst.MovieId = m.MovieID
join
Theaters t on t.ID = mst.TheaterId
join
Seances s on mst.SeanceId = s.ID
这是我对 Linq 查询的尝试:
var result = (from m in _context.Movies
join mst in _context.MovieSeanceTheaters on m.ID equals mst.MovieId
join t in _context.Theaters on mst.TheaterId equals t.ID
join s in _context.Seances on mst.TheaterId equals s.ID
select new { Film = m.Name, Salon = t.Name, Seans = s.Time }
).ToList();
我做了这个尝试,但我想用 lambda 例如:
var result = movieManager.GetAll().Where(x => x.MovieSeanceTheaters)....
我不能那样做。
解决方案
如果我对您的理解正确,您想将查询从查询语法重写为方法语法吗?
我们到了!
var result = _context.Movies
.Join(_context.MovieSeanceTheaters,
m => m.MovieID,
mst => mst.MovieID,
(m, mst) => new
{
m = m,
mst = mst
})
.Join(_context.Theaters,
temp0 => temp0.mst.TheaterID,
t => t.ID,
(temp0, t) =>
new
{
temp0 = temp0,
t = t
})
.Join(_context.Seances,
temp1 => temp1.temp0.mst.TheaterID,
s => s.ID,
(temp1, s) =>
new
{
Film = temp1.temp0.m.Name,
Salon = temp1.t.TheaterNumber,
Seans = s.Time
});
看起来很丑,不是吗?
大多数情况下,方法语法更加紧凑和方便。但在这种情况下,请保持原样。
推荐阅读
- django - 如何在 Django 3.0.8 中更改 USERNAME_FIELD。不创建自定义用户?
- r - R Shiny动态编辑reactiveTimer定时器间隔
- php - 在 laravel 6 中使用电子邮件或电话登录不起作用
- c++ - 如何从 Emscripten 触发事件?
- filter - 设置参数控制和使用过滤器
- kotlin - 带有自签名 ssl 证书的 GRPC Okhttp android 客户端通道
- xamarin - 我们可以在 uno 平台上减小 android App 的大小吗?
- java - 使用连接字符串通过 Spring Boot 连接到 Azure EventHub(Kafka like)
- javascript - 如何在 jqueryUI 小部件插件“多日期选择器”中设置动态参数值
- c# - mvvmcross WPF 显示用户对话框