How to add multiple dependent records in LINQ2SQL

I have two tables. One table contains comments for posts, the other contains comments such as an alias, site, etc. Relations between the two tables exist FK Comment .CommenterId β†’ Commenter.Id Whenever a user submits a comment, I need to add a comment and a commenter at the same time. The problem is that I don’t know what Commenter.Id will be after adding to assign it Comment.CommenterId before adding.

What is the best practice for such inserts?

+1
source share
1 answer

you can do it like this:

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();

- , , , .

+1

Source: https://habr.com/ru/post/1708529/


All Articles