views:

190

answers:

1

Hi. I have two tables. One table contains comments on posts, another contains commenter information like nickname, site, etc.. There is FK relations betwin two tables Comment.CommenterId -> Commenter.Id Whenever user posts a comment I need to add comment and commenter at the same time. The problem is that I don't know what would be Commenter.Id after addition to assign it to Comment.CommenterId before addition.

What is the best practice to do such inserts?

+1  A: 

you can do this like so:

Comment comment = new Comment(); // your constructor here
Commenter commenter = new Commenter(); // use your constructor;

comment.Commenter = commenter; // linq2sql creates this property for you.

datacontext.Commenter.InsertOnSubmit(commenter);
datacontext.Comment.InsertOnSubmit(comment);

datacontext.SubmitChanges();

this code has not been tested here in any way, so there may be syntax or other errors, but this is basically what you would need to do.

John Boker
You do not need the InsertOnSubmit(comment) if the tables are associated by a foreign Key
TGnat