How do I create two associated entities at one time with EF4 Code-First
So Say I have 2 entities, Post
and PostHistory
. Whenever I create or edit a p开发者_开发知识库ost, 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?
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.
精彩评论