我试图用带有一些测试数据 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; }
完全在实体到位桶:Post和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(默认),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 ;-)