How do I get the Entity Framework to initialise collections on my newly-created entities?

半腔热情 提交于 2019-12-10 02:56:34

问题


I'm trying to seed my database with some test data with an IDatabaseIntialiser like this:

protected override void Seed(BlogDataContext context)
{
    // <snip>
    var post = context.Posts.Create();
    post.Title = "My Life On Twitter";
    // <snip properties>

    // Set tags
    post.Tags.Add(aspnetTag); // NullRefException
    post.Tags.Add(razorTag);

Post entity looks like this:

public class Post
{
    // ...
    public virtual ICollection<Tag> Tags { get; set; }

Full entities at Bitbucket: Post and Tag. All code is at http://code.dantup.com/blog

However, post.Tags is null, so this doesn't work. Originally I was creating post as new Post(), however since I'm calling the Create method provided by the EF, why is the collection not initialised?

It feels clumsy to instantiate my own collection here, and if I do it in the constructor, presumably every time I load an entity from EF, it'll create the collection in the constructor and then overwrite it with one containing the actual data from the DB?

Is there some way to tell EF to create me an entity, including collections/proxies for my ICollections (assuming ICollection is the right choice)?

Edit: context.Configuration.ProxyCreationEnabled is set to true (by default), which seems to exist for this reason?


回答1:


With POCO entities and EF, I generally initialize collection in the constructor. And, I prefer ISet over ICollection ;-)



来源:https://stackoverflow.com/questions/5982254/how-do-i-get-the-entity-framework-to-initialise-collections-on-my-newly-created

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