1

I have two tables in my database in a 1:N relation and I would like to do a left join query with eager loading.

My tables are:

  • Videos (IDVIdeo, Name... )
  • Versions (IDVersion, IDVideo, Name, Avaliable...)

Well, in a video I can have many versions (DVD, Blu-Ray... etc) and a version only can belong to a video.

I would like to get all the videos which I have at least one available version (perhaps some version are in possession of one friend).

I would like to get all the videos that have at least avaliable version, but of this videos I want all the versions, avaliable and not avaliable.

So the first step is to know all the videos that have at least ona avaliable version and the second step is to get all the videos and all their versions (avaliable and not avaliable).

I would like to that with raw sql but how it is not possible to use eager loading with raw sql, I would like to use linq.

I want to use eager loading to use only one query to the database and not many, and because I would like to populate the collection versions in the video entity with its versions.

Thanks.

4

1 回答 1

1

使用 LINQ 的解决方案相当简单,并且是:

var videos = context.Videos
    .Include(v => v.Versions)
    .Where(v => v.Versions.Any(vers => vers.Available))
    .ToList();

如果您真的更喜欢原始 SQL,您可以从此 LINQ 查询中提取 SQL:

var sql = context.Videos
    .Include(v => v.Versions)
    .Where(v => v.Versions.Any(vers => vers.Available))
    .ToString();

编辑

使用原始 sql 的查询很可能不会填充导航属性,因此似乎无法将其用于预加载。请参阅此处的讨论,在答案及其评论中。

于 2013-07-28T10:16:10.577 回答