EF 4.1 代码优先:如何选择具有集合属性计数的实体
我有一个名为 Tag
的实体,其导航属性(集合)名为 Articles
。 标签
有一个名为ArticleCount
的忽略属性,用于保存关联的文章
计数(仅在运行时并在视图中使用 - 针对数据库忽略)。请参阅:
public class Tag{
public int Id { get; set; }
public int Title { get; set; }
public virtual ICollection<Article> Articles { get; set; }
[NotMapped]
public int ArticleCount { get; set; }
}
如何在 ONE< 中选择所有 Tag
(或一个)及其 ArticleCount
/strong> 查询实体框架 4.1 代码优先中的数据库,使用 lambda 表达式好吗?
I have an entity named Tag
with a navigation property (collection) named Articles
. The Tag
has a ignored-property named ArticleCount
that used to save tha associated Article
s count (just in run-time and to use in views- ignored against the DB). See:
public class Tag{
public int Id { get; set; }
public int Title { get; set; }
public virtual ICollection<Article> Articles { get; set; }
[NotMapped]
public int ArticleCount { get; set; }
}
How can I select all Tag
s (or one) with it's ArticleCount
in ONE query against the dataBase -in entity framework 4.1 code-first, with lambda expressions please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(我会以不同的方式设计它 -
ArticleCount
不应该是模型的一部分,或者它应该是Articles
上的投影,您可以使用Include 预先加载它()
。但这就是你想要的)更新:我的设计。
当然,这是否表现良好取决于每个标签的预期文章数。如果有几十个,这将合理地工作,同时比其他方法更干净。如果是数百个,则另一个更好。
现在,如果是这种情况,您应该使用匿名或命名的表示类型,而不是重用该实体。
(I would design this differently -
ArticleCount
should not be part of the model, or it should be a projection onArticles
, which you could eager-load usingInclude()
. But this does what you want)Update: my design.
Of course, whether this performs well or not depends on the the expected article count per tag. If it's a few dozen, this will work reasonably, while being cleaner than the other approach. If it's hundreds, the other one is better.
Now, if that's the case, you should use an anonymous or named presentation type instead of reusing the entity.
所有标签的示例:
这只是一个查询,并且复制发生在内存中。我相信除了将
ArticleCount
从匿名结果对象复制到标签中之外没有其他方法,因为您无法直接投影到实体中,因此您不能使用Select(t => ; 新标签 { ... });
。您可以使用另一个命名类型来代替匿名类型,但不能使用实体类型。Example for all tags:
This is only one query and the copy happens in memory. I believe that there is no other way than copying the
ArticleCount
from the anonymous result objects into the tags because you cannot project directly into an entity, so you can't useSelect(t => new Tag { ... });
. You could use another named type instead of the anonymous type but not an entity type.