我正在尝试用一些测试数据来种子我的数据库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()
,但是因为我打电话给Create
EF提供的方法,为什么集合没有初始化?
在这里实例化我自己的集合感觉很笨拙,如果我在构造函数中这样做,大概每次我从 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?