Friday, 15 April 2011

c# - adding a new item directly or indirectly (through the related class) in code-first entityframework -


There are two categories: Posts and comments Every post can have many comments, but each comment is only related to a post. Might be possible. If I want to add a new comment to the database, then I suppose it can either:

  MyDbContext db = new MyDbContext (); Comment c = new comment (); C.CommentText = commenttext; C.PostId = pid; Db.Comments.Add (c); Db.SaveChanges ();  

Or this:

  MyDbContext db = New MyDbContext (); Comment c = new comment (); C.CommentText = commenttext; Db.Posts.Single (P = & gt; p.PostId = postid) .Comments.Add (c); Db.SaveChanges ();  

I wonder which is better, I think that the second way can be more effective before another approach, I additionally load the post of memory though, the second In the approach, I do not do this, I do not do that. Can someone understand me the difference (if any)?


No comments:

Post a Comment