简体   繁体   中英

IQueryable<T> Join with Where Condition Entity Framework 6.0

I am trying to use where condition with IQueryable<T> Join approach but find no resources to give me clue how how to filter records based on child table field.

eg Normal query that I want to execute via IQueryable<T> Linq Statement:

Select 
    m.* 
from 
    vsk_media as m 
inner join 
    vsk_media_album as v 
on 
    m.id=v.mediaid 
where 
    v.albumid=47

Here is my code which works well without where statement:

IQueryable<vsk_media> Query = entities.vsk_media;
       Query.Join(entities.vsk_media_albums
       , c => c.id
       , cm => cm.mediaid
       , (c, cm) => new { c, cm });

Now how to add where condition to match with child table vsk_media_albums (where v.albumid=47) in above IQueryable Statement.

I tried my best to find solution but not found any good resource in web. I am not interested in normal Linq Statement.

You could try this using extension methods:

var query = entities.vsk_media
                    .Join(entities.vsk_media_album, 
                          m => m.id,
                          v => v.mediaid,
                          (m, v) => new { m, v })
                    .Where(x => x.v.albumid == 47)
                    .Select(x => x.m);

var list = query.ToList();

Or using the linq structure:

var query = from m in entities.vsk_media
            join v in entities.vsk_media_album on m.id equals v.mediaid
            where v.albumid = 47
            select m;

var list = query.ToList();

I know this has already been answered, but you should have navigations properties set up on vsk_media, then you can do this (assuming you navigation property from media to media_album is called "Albums"):

var list = entities.vsk_media
  .Include(m=>m.Albums)
  .Where(m=>m.Albums.albumid==47);

If you don't need the album info beyond just filtering based on it, then you can do this:

var list = entities.vsk_media
  .Where(m=>m.Albums.albumid==47);

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