【发布时间】:2011-08-24 08:18:23
【问题描述】:
我正在尝试使用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 和 Tag。所有代码都在http://code.dantup.com/blog
但是,post.Tags 为空,所以这不起作用。本来我是用new Post()创建帖子的,但是由于我调用的是EF提供的Create方法,为什么集合没有初始化?
在这里实例化我自己的集合感觉很笨拙,如果我在构造函数中这样做,大概每次我从 EF 加载实体时,它都会在构造函数中创建集合,然后用包含实际的集合覆盖它数据库中的数据?
有没有办法告诉 EF 为我创建一个实体,包括我的 ICollections 的集合/代理(假设 ICollection 是正确的选择)?
编辑:context.Configuration.ProxyCreationEnabled 设置为 true(默认),which seems to exist for this reason?
【问题讨论】:
-
看这里:prodinner.codeplex.com 在源代码中,至少 EF4.1 CodeFirst POCO 不需要集合初始化
-
@Omu - 我使用的是 EF4.1,但集合在创建时为空,但看起来与他们的相同
-
你能告诉我们你的实体吗?
标签: .net asp.net-mvc entity-framework sql-server-ce ef-code-first