如何将 EF4 Code-First ICollection 转换为 EntityCollection?

发布于 2024-10-17 23:34:02 字数 569 浏览 2 评论 0原文

假设我有以下实体:

public class Post
{
    public int Id { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

当我从数据库检索 Post 对象时,我需要将 Comments 集合转换为 EntityCollection 以便我可以检查一些有关集合的 EF4 相关数据,例如数据是否已预先加载。

不幸的是,如果我尝试从 ICollection 直接转换为 EntityCollection,由于 Comments< /code> 属性是 System.Collections.Generic.List,无法转换为 EntityCollection

那么,在使用代码优先时,如何获取集合上的 EF 信息呢?

Say I have the following entity:

public class Post
{
    public int Id { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

When I retrieve a Post object from the database, I need to convert the Comments collection into an EntityCollection<T> so that I can check some EF4 related data about the collection, such as if the data was eager loaded or not.

Unfortunately, if I try to do a direct cast from ICollection<T> to EntityCollection<T>, I get an exception due to the fact that the Comments property is a System.Collections.Generic.List<T> and cannot be converted into an EntityCollection<T>.

So how do I go about getting EF information on a collection when using code-first?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

傻比既视感 2024-10-24 23:34:02

作为评论可能更合适,但我希望 EF4 专家能够对此做出回应并解释发生了什么。我不久前在CTP4上问过以下问题。 EF 4 Recipes 的作者给出了一个回应,他说在运行时,如果将集合声明为虚拟,则该集合将被创建为 EntityCollection,而 ICollection(提问者显然正在这样做)这显然不会发生。

此外,Rowan Miller(EF4 团队成员)编写了一个更高级的选项,提问者之前曾表示该选项不起作用。这是怎么回事?难道现在的CTP不支持,而之前的CTP支持吗?

在 CTP4 Code First 中使用 CreateSourceQuery

This might be more appropriate as a comment, but I'm hoping an EF4 guru can respond to this and explain what's going on. I asked the question below a while ago, on CTP4. One response was from the author of EF 4 recipes, saying that at runtime the collection would be created as EntityCollection if it was declared as virtual and ICollection (which the questioner is clearly doing) That's obviously not happening.

Also, Rowan Miller (who's on the EF4 team) wrote a more advanced option, which the questioner has previously indicated does not work. What's going on here? Does the current CTP not support this, while the previous one does?

Using CreateSourceQuery in CTP4 Code First

む无字情书 2024-10-24 23:34:02

只要您的 POCO 类满足更改跟踪代理创建的要求,代理将用 EntityCollection 对象替换 ICollection 属性。乍一看,您的类满足这些要求,但您还应该确保 ProxyCreationEnabled 选项 设置为 true。

As long as your POCO class meets the requirements for change tracking proxy creation, the proxy will replace the ICollection properties with EntityCollection objects. At first glance your class meets these requirements, but you should also make sure that the ProxyCreationEnabled option is set to true.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文