views:

36

answers:

0

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 = "Joe";
        page.Url = "mypage/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();

    }