问题描述
我有两个桌子.一个表格包含对帖子的评论,另一个表格包含评论者信息,例如昵称,网站等.两桌之间有FK关系Comment.CommenterId-> Commenter.Id每当用户发表评论时,我都需要同时添加评论和评论者.问题是我不知道添加后的Commenter.Id是什么,在添加之前将其分配给Comment.CommenterId.
I have two tables. One table contains comments on posts, another contains commenter information like nickname, site, etc..There is FK relations betwin two tablesComment.CommenterId -> Commenter.IdWhenever 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?
推荐答案
您可以这样做:
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.
这篇关于如何使用LINQ2SQL添加多个从属记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!