Using Entity Framework and queries without creating a large number of queries (excluding N + 1)

I am using a design template which after using the Entity Framework Profiler seems like it can be pretty stupid.

I expanded my entity classes to have properties that are filtered views of the collection associated with this object. Like this:

public IEnumerable<Member> ActiveMembers
{
    get
    {
        return Members.Where(t => t.LeftDate == null);
    }
}

Since I am mainly interested in members who have not left the club, this property was very useful and seemed to make sense.

However, from starting EF Profiler, I now know that this often leads to N + 1 problems. If I scroll through the elements and also want to show their address, then each request for the address leads to an additional db request.

, :

return Members.CreateSourceQuery().Include("Address")
              .Where(t => t.LeftClubDate == null);

N + 1, , .

, ActiveMembers, , . :

var membersToDisplay = ActiveMembers.Include("Address").ToList();

, ?

+3
1

, Include IEnumerable . Include - ObjectQuery/DbQuery. Include IQueryable ( EFv4.1 ), ObjectQuery DbQuery , . .

, , , .

N + 1. , linq:

var clubId = ActiveClub.Id;
var members = (from member in context.Members.Include("Address")
               where member.LeftDate == null and member.ClubId == clubId
               select member).ToList();
+3

All Articles