c# - How do I create two associated entities at one time with EF4 Code-First -


so have 2 entities, post , posthistory. whenever create or edit post, want create exact copy of posthistory log changes made post. post entity has 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 create first post. example, if 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 fail because since both post , history new entities, post.posthistory null due not having been initialized yet. way can see first commit post db, commit history database, don't see why performing 2 separate inserts should necessary this.

if have constructor initializes icollection list<t> works fine, forcing implementation list<t> causes other issues, , no code-first tutorials forced initiation.

so what's best way handle situation?

you can initialize list in client code itself:

post post = new post  {      text = "blah"      posthistory = new list()      {          new posthistory { text = "blah" }     } };         context.posts.add(post); context.savechanges(); 

however, there nothing wrong initializing collection inside constructor , recommended because saves having initialize in client codes.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -