c# - Insert new/Update existing record with one to many relationship -


i have 2 simple models creating database tables of entity framework:

public class blog  {      public int id { get; set; }      public string title { get; set; }      public virtual icollection<post> posts { get; set; }       public blog()      {         posts = new collection<post>();     } }   public class post  {      public int id { get; set; }      public string title { get; set; }      public string content { get; set; }      // foreign key of blog table     public int blogid { get; set; }  } 

now in db context have dbset generate database tables:

public dbset<blog> blogs { get; set; } 

database tables generated expected, question, how insert new blog posts db. i've tried this:

blog blog = context.blogs.firstordefault(b => b.title == blogtitle);  // no blog title yet, create new 1 if (blog == null) {     blog = new blog();     blog.title = blogtitle;      post p = new post();     p.title = posttitle;     p.content = "some content";      blog.posts.add(p);     context.blogs.add(blog); }  // blog exist, add post  else  {     post p = new post();     p.title = posttitle;     p.content = "some content";     context.blogs.firstordefault(b => b.title == blogtitle).posts.add(p); }  context.savechanges(); 

as can see not touching id , blogid, should generated entityframework automatically.

however, using code, blog getting inserted database, next time i'll try execute same code tell me posts collection of blog empty.

am doing wrong? there better practice doing insertion/update of records db 1 many relationship?

thank you

update:

thanks answers, able insert both blog , post db, however, post still not linked particular blog, blogid inside post table 0.

do need increment manually or maybe kind of attribute?

try adding

public blog blog { get; set; } 

property post , configure

          modelbuilder.entity<post >().hasrequired(n => n.blog)             .withmany(n=>n.posts )             .hasforeignkey(n => n.blogid)             .willcascadeondelete(true); 

in onmodelcreating(dbmodelbuilder modelbuilder) in context definition

then regenerate database


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -