Insert new/Update existing record with one to many relationship

.net asp.net c# dbcontext entity-framework

Accepted Answer

test adding

public Blog Blog { get; set; }

ability to post and set up

          modelBuilder.Entity<Post >().HasRequired(n => n.Blog)
            .WithMany(n=>n.Posts )
            .HasForeignKey(n => n.BlogId)
            .WillCascadeOnDelete(true);

in the context definition of OnModelCreating(DbModelBuilder modelBuilder)

Regenerate the database next.

2
8/19/2015 3:43:31 PM

Popular Answer

What should be said should be:

Blog blog = context.Blogs.FirstOrDefault(b => b.Title == blogTitle);

// no blog with this title yet, create a new one
if (blog == null) {
    blog = new Blog();
    blog.Title = blogTitle;
    blog.Posts = new Collection<Post>();
    context.Blogs.Add(blog);
} 

Post p = new Post();
p.Title = postTitle;
p.Content = "some content";
blog.Posts.Add(p);

context.SaveChanges();

Additionally, I would remove the constructor's initialization of Posts.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow