如何让实体框架初始化我新创建的实体的集合? [英] How do I get the Entity Framework to initialise collections on my newly-created entities?
问题描述
我正在尝试使用 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);
邮政实体如下所示:
public class Post
{
// ...
public virtual ICollection<Tag> Tags { get; set; }
Bitbucket的完整实体:和标签。所有代码均位于 http://code.dantup.com/blog
Full entities at Bitbucket: Post and Tag. All code is at http://code.dantup.com/blog
但是, post.Tags
为null,因此这不起作用。最初我正在创建一个新的Post()
的帖子,但是由于我正在调用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?
在这里我感觉到笨拙的实例化了我自己的收藏,如果我在构造函数中这样做,大概每次我加载一个实体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(默认情况下),似乎存在这个原因?
Edit: context.Configuration.ProxyCreationEnabled
is set to true (by default), which seems to exist for this reason?
推荐答案
使用POCO实体和EF,我通常在构造函数中初始化集合。而且,我更喜欢ISet over ICollection; - )
With POCO entities and EF, I generally initialize collection in the constructor. And, I prefer ISet over ICollection ;-)
这篇关于如何让实体框架初始化我新创建的实体的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!