开发者

linq to sql, insert many to many relationship

开发者 https://www.devze.com 2023-03-25 15:35 出处:网络
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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号