linq to sql, insert many to many relationship
I have 3 tables.
Post: PostID, PostName
Tag: TagID, TagName
PostTag: PostTagID, PostID, TagID
Following codes are how I insert many to many. but I use SubmitChanges() three times,I dont think that's the best way to do it. I can use stored procedure. but want to know if there's a better way to do it without stored procedure.
Post post = new Post()
{
PostName = entity.PostName
};
context.Posts.InsertOnSubmit(post);
开发者_StackOverflow中文版 context.SubmitChanges();
Tag tag = new Tag()
{
TagName = entity.Tags
};
context.Tags.InsertOnSubmit(tag);
context.SubmitChanges();
PostTag pt = new PostTag()
{
PostID = post.PostID,
TagID = tag.TagID
};
context.PostTags.InsertOnSubmit(pt);
context.SubmitChanges();
You don't need to SubmitChanges three times. If you have the proper foreign keys in place, you can simply add the references to each other in code then SubmitChanges once. LINQ is awesome like that.
Post post = new Post()
{
PostName = entity.PostName
};
context.Posts.InsertOnSubmit(post);
Tag tag = new Tag()
{
TagName = entity.Tags
};
context.Tags.InsertOnSubmit(tag);
PostTag pt = new PostTag()
{
Post = post,
Tag = tag
};
context.PostTags.InsertOnSubmit(pt);
context.SubmitChanges();
You can also call InsertOnSubmit only on one of these objects. Compare with Insert into many-to-many relationship tables
精彩评论