使用LINQ包含嵌套实体 [英] Include nested entities using LINQ

查看:95
本文介绍了使用LINQ包含嵌套实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是第一次弄乱LINQ,首先是使用EF 4.1代码.

I'm messing around with LINQ for the first time, and I'm using EF 4.1 code first.

我有一些包含其他实体嵌套列表的实体,例如:

I have entities containing nested Lists of other entities, for example:

class Release
{
    int ReleaseID { get; set; }
    string Title { get; set; }
    ICollection<OriginalTrack> OriginalTracks { get; set; }
}

class OriginalTrack
{
    int OriginalTrackID { get; set; }
    string Title { get; set; }
    ICollection<Release> Releases { get; set; }
    ICollection<OriginalArtist> OriginalArtists { get; set; }
}

class OriginalArtist
{
    int OriginalArtistID { get; set; }
    string Name { get; set; }
    ICollection<OriginalTrack> OriginalTracks { get; set; }
}

我想知道在一个LINQ查询中最快的方法是获取ReleaseID == some value位置的所有信息.

I'm wondering what is the quickest way, in one LINQ query, to obtain all the information for where ReleaseID == some value.

我已经完成作业,但是找到了一些解决方案,这些解决方案要求使用所需数据隐式重建对象(通常是匿名对象).我希望数据以数据库中保留的确切格式从数据库中移出,即,使用相关的ReleaseID拉动Release对象,从而拉出并填充列表中的所有OriginalTrack和OriginalArtist数据.

I've done my homework, but have found solutions that require implicit rebuilding of an object (usually anonymous) with the required data. I want the data out of the database in the exact format that it is held within the database, i.e. pulling a Release object with relevant ReleaseID pulls and populates all the OriginalTrack and OriginalArtist data in the Lists.

我了解Include(),但是不确定如何将其应用于多个实体.

I know about Include(), but am not sure how to apply it for multiple entities.

非常感谢所有帮助.

推荐答案

不用担心在此处使用包含

Don't worry about using include here

只需执行以下操作

var query = 
    from release in ctx.Releases
    select new {
        release,
        originalTracks = from track in release.OriginalTracks
                         select new {
                               track,
                               releases = track.Releases,
                               orignialArtist = from artist in track.OriginalArtists
                                                select new {
                                                     artist,
                                                     artist.OriginalTracks
                                                }
                         }
        }

var Releases = query.Select(x => x.Release);

应加载所有数据

我在这里处理了这篇文章中的信息.

I worked with information from this post here.

http://blogs.msdn.com/b/alexj/archive/2009/10/13/tip-37-how-to-do-a-conditional-include.aspx

这篇关于使用LINQ包含嵌套实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆