سؤال

In the famous Blog/Post example, we see that how Blog entity is saved.

public class Blog 
{ 
     public int BlogId { get; set; } 
     public string Name { get; set; } 

     public virtual List<Post> Posts { get; set; } 
} 

public class Post 
{ 
     public int PostId { get; set; } 
     public string Title { get; set; } 
     public string Content { get; set; } 

     public int BlogId { get; set; } 
     public virtual Blog Blog { get; set; } 
}

Save Blog is simple:

        var blog = new Blog { Name = name }; 
        db.Blogs.Add(blog); 
        db.SaveChanges(); 

But I am not sure how to save Post since it is a List.

What I did was:

            foreach (var item in Posts)
            {
                Post p = new Post();
                p.Title = item.Title;
                p.Content = item.Content;
                SaveChanges();
            }

It works out of course, but if Posts contains many items then we have to save many times. It is inefficient, how can we save it just once?

هل كانت مفيدة؟

المحلول

There's two ways you can do this, either by adding to blog.Posts and having Entity Framework setup the foreign keys automatically:

Blog blog = new Blog 
{ 
    Name = name,
    Posts = new List<Post>()
}; 

foreach (var item in posts)
{
    Post p = new Post();
    p.Title = item.Title;
    p.Content = item.Content;

    blog.Posts.Add(p);
}

db.Blogs.Add(blog); 
db.SaveChanges(); 

or by adding to the Posts table directly:

// assuming you have a reference to the blog id in blogId

foreach (var item in posts)
{
    Post p = new Post();
    p.BlogId = blogId;
    p.Title = item.Title;
    p.Content = item.Content;

   db.Posts.Add(p);
}

db.SaveChanges();

You can add as many items as you'd like, but then call SaveChanges() once, and it'll only make one trip to the database.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top