如何让实体框架初始化新创建的实体上的集合?

2024-05-12

我正在尝试用一些测试数据来种子我的数据库IDatabaseIntialiser像这样:

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

帖子实体如下所示:

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

Bitbucket 上的完整实体:Post https://bitbucket.org/DanTup/dantup-blog/src/03cfceba726b/DanTup%20Blog/Models/Post.cs and Tag https://bitbucket.org/DanTup/dantup-blog/src/03cfceba726b/DanTup%20Blog/Models/Tag.cs。所有代码位于http://code.dantup.com/blog http://code.dantup.com/blog

然而,post.Tags为空,所以这不起作用。最初我创建的帖子是new Post(),但是因为我打电话给CreateEF提供的方法,为什么集合没有初始化?

在这里实例化我自己的集合感觉很笨拙,如果我在构造函数中这样做,大概每次我从 EF 加载实体时,它都会在构造函数中创建集合,然后用包含来自 EF 的实际数据的集合覆盖它。 D B?

有没有什么方法可以告诉 EF 创建一个实体,包括我的集合/代理ICollections(假设ICollection是正确的选择)?

Edit: context.Configuration.ProxyCreationEnabled设置为 true (默认情况下),这似乎是因为这个原因而存在的 http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbcontextconfiguration.proxycreationenabled(v=vs.103).aspx?


对于 POCO 实体和 EF,我通常在构造函数中初始化集合。而且,我更喜欢 ISet 而不是 ICollection ;-)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让实体框架初始化新创建的实体上的集合? 的相关文章

随机推荐