Entity Framework - InverseProperty and IQueryable (or equivalent)

I'm still pretty new to EF (v4.1), so correct me if I'm wrong, but if I have InverseProperty then:

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

This will be lazy when loading a property. However, if I want to filter this list - for example, to receive only active comments, I could simply add another property as follows:

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

However, the entire collection of comments will be loaded first, and then the filter is correct? So not using IQueryable? For performance, ideally I would like to get a list using IQueryable.

So my question is: can this be done using an object property like this? Or I will have to do what directly in ItemComments:

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

This will obviously work ... but in the future I wonder if there is a better solution?

Update. It seems that the entire result set is loaded, and any filtering will be performed on the entire client side of the data set. Other than hacks or changing the object to pass context to (yuck!), There seems to be no built-in way to do this. The answer was @Slauma's answer.

+4
source share
1 answer

will load the entire collection of comments first and then filter it right?

Yes.

this can be done using the property of the object

Theoretically, by entering a repository or even context into an entity constructor. But you will have a dependency on your POCO objects at the data access level. I would not like this solution.

Your proposed solution is a way. You can also use explicit loading:

 itemRepository.LoadActiveComments(item); 

Implemented as follows:

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

Source: https://habr.com/ru/post/1446485/


All Articles