繁体   English   中英

如何在实体框架中使用 lambda 表达式进行此查询?

[英]How to make this query with lambda expression in Entity Framework?

这是我的 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
            });

看起来很丑,不是吗?
大多数情况下,方法语法更加紧凑和方便。 但在这种情况下,请保持原样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM