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?