MaciejLisCK
MaciejLisCK

Reputation: 3984

Get entity with filtered inner entities - EF

I have got entity:

Entry
{
    public virtual ICollection<Content> Contents { get; set; }
}

I need to get the Entry that contains filtered Contents.

var entryWithFilteredContents = dbContext.Entry.Single(). ???
    /*Load(entry=>entry.Contents) Where(content=> content.Value > 10)*/

Now when I write entryWithFilteredContents.Contents I expect to receive only contents that have Value greater then 10. I know i can get an var entry = db.Context.Entry.Single() and then var contents = entry.Contents.Where(content=> content.Value > 10) but that don't satisfy my needs.

Upvotes: 0

Views: 76

Answers (1)

Morten Mertner
Morten Mertner

Reputation: 9474

This is not something EF currently supports out of the box.

The usual workaround is to first select a projection, like this:

var query = from e in dbContext.Entry
            select new { Entry = e, Related = e.Contents.Where(c => c.Value > 10) };
return query.Where(p => p.Related.Count > 0).Select(p => p.Entry);

You can of course also return any projection directly (and potentially save some database round-trips), but will need a non-anonymous type in order to have the result escape the current method.

Upvotes: 1

Related Questions