简体   繁体   中英

Entity Framework - InverseProperty and IQueryable (or Equivalent)

I'm still fairly new to EF (v4.1), so correct me if I'm wrong, but if I have an InverseProperty as follows:

public virtual ICollection<ItemComment> Comments { get; set; }

This will be lazy loaded when the property is accessed. However, if I wish to filter this list - for example, to get only active comments, I could just add another property as follows:

public IEnumerable<ItemComment> ActiveComments {
    get { return Comments.Where(x => x.IsActive); }
}

However, this will load the entire Comments collection first, and then filter right? So not using IQueryable? For performance, ideally I'd like to get the list using IQueryable.

So my question is, can this be done using a property of an entity like this? Or am I going to have to do a where on the ItemComments directly:

var comments = itemCommentRepository.QueryAll()
    .Where(x => x.IsActive && x.ItemId == XX).

This will obviously work... but going forward I wonder if there's a better solution?

Update: It seems the entire result set IS loaded, and any filtering would be done on the whole dataset client-side. Aside from hacks, or changing the entity to pass the context in (yuck!), there doesn't appear to be an in-built way to do so. Have marked @Slauma's response as the answer.

this will load the entire Comments collection first, and then filter right?

Yes.

can this be done using a property of an entity

In theory, by injecting the repository or even a context into the entity constructor. But you would have a dependency of your POCO entities on a data access layer. I would not like this solution.

Your proposed solution is a way. You could alternatively use explicit loading:

itemRepository.LoadActiveComments(item);

Implemented like this:

void LoadActiveComments(Item item)
{
    context.Entry(item).Collection(i => i.Comments).Query()
        .Where(c => c.IsActive).Load();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM