How can I convert an EF4 Code-First ICollection to an EntityCollection?

孤街醉人 提交于 2019-12-08 01:52:36

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/5035757/how-can-i-convert-an-ef4-code-first-icollection-to-an-entitycollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!