开发者

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

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 clu开发者_C百科msy 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜