Entity Framework 4.0 only include some related dat

2019-09-04 13:01发布

问题:

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?

回答1:

If lazy loading is on, it will in fact lazily load stuff that you reference. If you don't want it enabled, then turn it off.

myContext.Configuration.LazyLoadingEnabled = false;

You can specify that you want certain things loaded in the initial database round-trip so that lazy loading is not necessary. There, Include is your friend.

using System.Data.Entity; // You need this to get the lambda version of Include

from s in myContext.Sales.Include(s => s.PropertyA).Include(s => s.PropertyB)
select s;

Note that you can always disable lazy loading for specific properties by not declaring them virtual.

I recommend the following blog for a great overview

http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx



回答2:

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