简体   繁体   中英

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

This is my SQL query:

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

This is my attempt at a Linq query:

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();

I made this attempt, but I want to make with lambda for instance:

var result = movieManager.GetAll().Where(x => x.MovieSeanceTheaters).... 

I couldn't do that.

If I understand you correctly, you want to rewrite your query from query syntax to method syntax?

Here we are!

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
            });

Looks ugly, doesn't it?
Most often, the method syntax is more compact and convenient. But in this case, leave it as is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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