Include nested entities using LINQ

前端 未结 3 1506
梦如初夏
梦如初夏 2020-12-28 16:45

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:



        
相关标签:
3条回答
  • 2020-12-28 16:58

    To include the nested entities without using string literals, use Select, like this:

    context.Releases.Include(r => r.OriginalTracks.Select(t => t.OriginalArtist))
        .Where(release => release.ReleaseID == id);
    
    0 讨论(0)
  • 2020-12-28 17:09

    Use Include. This is the purpose of Include, and there's no reason to write a bunch of nested select statements.

    context.Releases.Include("OriginalTracks.OriginalArtist")
        .Where(release => release.ReleaseID == id);
    

    This is simpler to write, simpler to read, and preserves your existing data structure.

    To use Include you need to specify the name of the property you want to return - this means the name as it exists in your code, not in the database. For example:

    • .Include("OriginalTracks") will include the OriginalTracks property on each Release
    • .Include("OriginalTracks.OriginalArtist") will include OriginalTracks property on each Release, and the OriginalArtist on each Track (note that it's not possible - syntactically or logically - to include an OriginalArtist within including the OriginalTrack)
    • .Include("OriginalTracks").Include("OtherProperty") will include the OriginalTracks and OtherProperty objects on each Release.

    You can chain as many of these as you like, for example:

    .Include("Tracks.Artist").Include("AnotherProperty")
        .Include("ThirdProperty.SomeItems").Where(r => r.something);
    

    is perfectly valid. The only requirement is that you put the Include on the EntitySet, not on a query - you can't .Where().Include().

    0 讨论(0)
  • 2020-12-28 17:22

    Don't worry about using include here

    just do something like the following

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

    Should load all of your data

    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

    0 讨论(0)
提交回复
热议问题