如何获得实体框架初始化集合在我的新创建的实体? [英] How do I get the Entity Framework to initialise collections on my newly-created entities?

查看:198
本文介绍了如何获得实体框架初始化集合在我的新创建的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用带有一些测试数据 IDatabaseIntialiser 这样的种子我的数据库:

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; }

完全在实体到位桶:<一href="https://bitbucket.org/DanTup/dantup-blog/src/03cfceba726b/DanTup%20Blog/Models/Post.cs">Post和<一href="https://bitbucket.org/DanTup/dantup-blog/src/03cfceba726b/DanTup%20Blog/Models/Tag.cs">Tag.所有code是在 HTTP://$c$c.dantup.com/blog

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

不过, post.Tags 为空,所以这是行不通的。本来我是创造岗位作为新邮(),但是因为我打电话的EF提供的创建方法为什么是集不会被初始化?

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?

感觉笨拙在此实例我自己的收藏,如果我这样做,在构造函数中,presumably每次我打开从EF的实体,它会在构造函数中创建的集合,然后有一个覆盖它从数据库中包含实际数据?

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?

是否有某种方式来告诉EF创建我的实体,包括集合/代理我的 ICollections (假设的ICollection 是正确的选择)?

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

修改 context.Configuration.ProxyCreationEnabled 设置为true(默认),<一个href="http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbcontextconfiguration.proxycreationenabled%28v=vs.103%29.aspx">which似乎存在这个原因?

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

推荐答案

使用POCO实体和EF,我一般初始化集合中的构造。而且,我preFER的ISet过的ICollection; - )

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

这篇关于如何获得实体框架初始化集合在我的新创建的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆