Search code examples
linqc#-4.0entity-framework-4

Entity Framework 4.0 only include some related data


I want my query results to only inlcude some of the reated data. For instatnce say I have the entities Sale and Item with each Sale having an Items property which is a list of Item for a particular Sale:

from s in myContext.Sales
select s;

returns all Sales with each Sale containing all Items (when I navigate to Items as LazyLoading is on by default). But I want to only include specifc Items for each Sale - say Items where Name == "Orange" and I still want all Sales. How can I do this?


Solution

  • My answer is specific to EF 4.0 and mostly got from here: http://msdn.microsoft.com/en-us/library/bb896249.aspx

    Prevent LazyLoading loading everything when a navigation property is accessed:

    myContext.Configuration.LazyLoadingEnabled = false;
    

    Load you items:

    List<Sale> sales = (from s in myContext.Sales
                        select s).ToList()
    

    Foreach item Attach its related items you want (the key to getting only some items is the CreateSourceQuery() method):

    foreach(Sale s in sales)
        s.Items.Attach(s.Items.CreateSourceQuery().Where(i => i.Name == "Orange"));