Insert record in Linq to Sql

Posted by Anders Svensson on Stack Overflow See other posts from Stack Overflow or by Anders Svensson
Published on 2010-05-30T21:28:05Z Indexed on 2010/05/30 21:42 UTC
Read the original article Hit count: 411

Is this the easiest way to insert a record with Linq to Sql when there's a many-to-many relationship, or is there a better/cleaner way? I wasn't sure why things weren't working at first, but when I added a second SubmitChanges() it worked. Why was this necessary? Would be grateful if someone could clarify this a bit!

private void InsertNew()
    {

        UserPageDBDataContext context = new UserPageDBDataContext();

        User user = new User();
        ManyToMany.Model.Page page = new ManyToMany.Model.Page();

        user.Name = "Madde Andersson";
        page.Url = "anderscom/references";

        context.Users.InsertOnSubmit(user);
        context.Pages.InsertOnSubmit(page);

        context.SubmitChanges();

        UserPage userPage = new UserPage();
        userPage.UserID = user.UserID;
        userPage.PageID = page.PageID;
        user.UserPages.Add(userPage);

        context.SubmitChanges();

    }

© Stack Overflow or respective owner

Related posts about linq-to-sql

Related posts about gridview