简体   繁体   English

如何使用EF4 Code-First一次创建两个关联实体

[英]How do I create two associated entities at one time with EF4 Code-First

So Say I have 2 entities, Post and PostHistory . 所以说我有2个实体, PostPostHistory 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. 每当我创建或编辑帖子时,我都想创建一个精确的帖子副本作为PostHistory来记录对帖子所做的所有更改。 Say the post entity has the following definition: 假设post实体具有以下定义:

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 . 当我创建我的第一个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. 这将失败,因为posthistory都是新实体, Post.PostHistory因为尚未初始化而为null。 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. 我可以看到这样做的唯一方法是首先将post提交到db,然后将history提交到数据库,但我不明白为什么为此需要执行2个单独的插入。

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. 如果我有一个构造函数将ICollection初始化为List<T>一切正常,但强制实现到List<T>会导致其他问题,而且几乎没有代码优先的教程会强制启动。

So what's the best way to handle this situation? 那么处理这种情况的最佳方法是什么?

You can initialize the list in the client code itself: 您可以在客户端代码本身中初始化列表:

Post post = new Post 
{ 
    Text = "Blah" 
    PostHistory = new List() 
    { 
        new PostHistory { Text = "Blah" }
    }
};        
context.Posts.Add(post);
context.SaveChanges();

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. 但是,在构造函数中初始化集合没有任何问题,实际上建议使用它,因为它使您不必在所有客户端代码中初始化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM