简体   繁体   English

实体框架-InverseProperty和IQueryable(或等效项)

[英]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: 我对EF(v4.1)还是很陌生,所以如果我错了,请更正我,但是如果我有一个InverseProperty,如下所示:

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? 但是,这将首先加载整个Comments集合,然后进行过滤,对吗? So not using IQueryable? 所以不使用IQueryable吗? For performance, ideally I'd like to get the list using IQueryable. 为了提高性能,理想情况下,我想使用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: 还是我必须直接在ItemComments上执行以下操作:

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. 已将@Slauma的回复标记为答案。

this will load the entire Comments collection first, and then filter right? 这将首先加载整个Comments集合,然后进行过滤,对不对?

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. 但是您将在数据访问层上依赖POCO实体。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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