如何使用 EF4 Code-First 同时创建两个关联实体
假设我有 2 个实体,Post
和 PostHistory
。每当我创建或编辑帖子时,我都想创建它的精确副本作为 PostHistory
来记录对帖子所做的所有更改。假设帖子实体具有以下定义:
public class Post
{
public int Id { get; set; }
public string Text { get; set; }
public virtual ICollection<PostHistory> PostHistory{ get; set; }
}
当我创建第一个 Post
时,问题就出现了。例如,如果我尝试这样做:
Post post = new Post { Text = "Blah" };
context.Posts.Add(post);
PostHistory history = new PostHistory { Text = "Blah"};
context.PostHistory.Add(history);
post.PostHistory.Add(history);
那将会失败,因为 post
和 history
都是新实体,因此 Post.PostHistory
为 null尚未初始化。我能看到做到这一点的唯一方法是首先将 post
提交到数据库,然后将 history
提交到数据库,但我不明白为什么要执行 2 个单独的插入为此应该是必要的。
如果我有一个将 ICollection
初始化为 List
的构造函数,一切正常,但强制实现 List
会导致其他问题,并且几乎没有代码优先教程会执行此强制启动。
那么处理这种情况的最佳方法是什么?
So Say I have 2 entities, Post
and PostHistory
. Whenever I create or edit a post, I want to create an exact copy of it as PostHistory
to log all changes made to a post. Say the post entity has the following definition:
public class Post
{
public int Id { get; set; }
public string Text { get; set; }
public virtual ICollection<PostHistory> PostHistory{ get; set; }
}
The problem comes when I create my first Post
. For example, if I try this:
Post post = new Post { Text = "Blah" };
context.Posts.Add(post);
PostHistory history = new PostHistory { Text = "Blah"};
context.PostHistory.Add(history);
post.PostHistory.Add(history);
That will fail because since both post
and history
are new entities, Post.PostHistory
is null due to it not having been initialized yet. The only way I can see to do this is to first commit post
to the db, then commit history
to the database, but I don't see why performing 2 separate inserts should be necessary for this.
If I have a constructor that initializes the ICollection
to a List<T>
everything works fine, but forcing the implementation to List<T>
causes other issues, and almost no code-first tutorials do this forced initiation.
So what's the best way to handle this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在客户端代码本身中初始化列表:
但是,在构造函数内初始化集合没有任何问题,实际上建议这样做,因为它使您不必在所有客户端代码中初始化它。
You can initialize the list in the client code itself:
However, there is nothing wrong with initializing the collection inside the constructor and it is actually recommended because it saves you from having to initialize it in all the client codes.