Linq-to-sql Add item and a one-to-many record at once
- by Oskar Kjellin
I have a function where I can add articles and users can comment on them. This is done with a one to many relationship like= "commentId=>ArticleId". However when I try to add the comment to the database at the same time as I add the one to many record, the commentId is not known. Like this code:
Comment comment = new Comment();
comment.Date = DateTime.UtcNow;
comment.Text = text;
comment.UserId = userId;
db.Comments.InsertOnSubmit(comment);
comment.Articles.Add(new CommentsForArticle() { ArticleId = articleId, CommentId = comment.CommentId });
The commentId will be 0 before i press submit. Is there any way arround not having to submit in between or do I simply have to cut out the part where I have a one-to-many relationship and just use a CommentTable with a column like "ArticleId".
What is best in a performance perspective?
I understand the underlying issue, I just want to know which solution works best.