This article reproduced: http://www.cnblogs.com/brusehht/archive/2010/09/01/1814962.html
Problem description
Some friends want to use such a query, such as to query the movies entity object, but also want to load the relevant reviews object by preloading, but also want to load only eligible parts of reviews.
Unfortunately, EF does not meet such functional objectquery<movie> Include (...) Method can only load all or all without loading.
var dbquery=ctx. Movies.include ("reviews"). Where (G=>g.genre = = "Horror")
Solution Solutions
The following workarounds can implement the above requirements:
public class Movie
{
public int ID {get;set;}
public string Name {get;set;}
public string Genre {get;set;}
Public list<review> Reviews {Get;set;}
}
public class Review
{
public int ID {get;set;}
public int Stars {get;set;}
public string Summary {get;set;}
Public movie movie {Get;set;}
Public user user {Get;set;}
}
Suppose you want to get the movie "horror" as described in the reviews with 5 stars, you can like this:
var dbquery =
From movie in CTX. Movies
where movie. Genre = = "Horror"
Select New {
Movie
Reviews = from review in movie. Reviews
where review. Stars = = 5
Select Review
};
var movies = Dbquery
. AsEnumerable ()
. Select (M = M.movie);
Now take a look at why the above code is successfully executed?
First, the first query creates a new instance of all the horror movies and their reviews containing 5 stars.
The second query uses the LINQ to Object AsEnumerable () method to make a memory query, simply using a non-unpacking method from the anonymous type to get the relevant instance, in each movie will contain the filtered reviews.
So the following code assertion will pass,
foreach (var movie in movies)
{
foreach (Var review in movie. Reviews)
Assert (review. Rating = = 5);
}
The code above can be implemented because EF introduces a mechanism called relationship fix-up.
Relationship Fix-up assumes that all related objects will be automatically hooked up when the second entity object enters the Obectcontext. Here we're talking about objects loaded into the ObjectContext with only the corresponding movie and filtered related REVIEWS,EF the default is that they have been automatically hooked up, which means that those filtered reviews will automatically populate the review array of the movie.
In short, this relationship fix-up way (which I call relationship improvement) will be applied to your advanced applications.
How to implement Conditional Include