EF include with where clause

c# entity-framework linq

Accepted Answer

Try using include in the following manner:

var query = _context.MemberPoint.Include("Resource.ResourceDetails")
                                .Where(m => m.MemberId == 111111);

Alternatively, consider joining on resourceId and choosing an anonymous type with the appropriate data:

var query = (from m in _context.MemberPoint
            join rd in _context.ResourceDetails on m.ResourceId equals rd.ResourceId
            where m.MemberId == 11111
            select new
               Member = m,
               ResourceDetail = rd
12/30/2014 3:33:47 AM

Popular Answer

You are utilizing EF entirely in the wrong way.

Actually, what you want is

When ResourceDetails has a single resource and each resource contains a single member (unlikely).

var query = _context.ResourceDetails
        .Include(d => d.Resource)
        .Include(r => r.Resource.Memberpoints)
        .Where(d => d.Resource.Memberpoints.MemberId == 1);

If each resource in ResourceDetails has a number of members, then there is only one resource.

var query = _context.ResourceDetails
        .Include(d => d.Resource)
        .Include(r => r.Resource.Memberpoints)
        .Where(d => d.Resource.Memberpoints.Any(m => m.MemberId == 1));

If ResourceDetails has many Resources, each of which could have multiple Members, which is rare.

var query = _context.ResourceDetails
        .Include(d => d.Resource)
        .Include(r => r.Resource.Memberpoints)
        .Where(d => d.Resource.Any(r => r.Memberpoints.Any(m => m.MemberId == 1)));

Okay. What about the joining you sought? Well that is the job of the ORM. The ORM mapping is aware of howResourceDetails are connected toMembers .

What was the error you received, then?

The signature ofIQueryable.Where() taking aFunc<T, bool> and yields anIQueryable<T> .

As a result, in your case, the innerWhere is incorrect as you're giving it aFunc<T, int> The outsiderWhere is incorrect given that you are passing aIQueryable<T> to it (but the compiler is unaware of this because it is already completely incorrect).


Avoid joining with EntityFramework or Linq in general. EF should already know how to connect entities together and should have the associations in the mappings.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow