Question about adding records in intermediate table

3 posts, 0 answers
  1. Daniel Plomp
    Daniel Plomp avatar
    130 posts
    Member since:
    Feb 2004

    Posted 01 Sep 2010 Link to this post

    Hi all,

    I've a database with the following tables:

     

    • Person
    • Role
    • Person_Role

    I can get Roles out of a Person and vice versa. Works okay.
    Now I have to add a function that can add a Person into a Role (as needed bij the MembershipProvider).

    So, how can I do this within LINQ?
    Since the OpenAccess Model doesn't show the intermediate table, which I believe it the right approach, I still don't get how to do this.

    I came up with this code, but I doubt if that is the right way:

    public void AddPersonToRole(string rolename, string username)
    {
       try
       {
          Person p = GetPerson(username);
          Role r = GetRole(rolename);
      
          p.Roles.Add(r);
          context.SaveChanges();
       }
       catch (Exception ex)
       {
          throw ex;
       }
    }

    How should I deal with this intermediate thing? (m:m)

    Thanks,
    Daniel

  2. TSE
    TSE avatar
    381 posts
    Member since:
    Sep 2008

    Posted 01 Sep 2010 Link to this post

    Hi Daniel,

    What you did should do the trick... if the m:n relationship is managed. If not, you as the developer should handle both sides of the association (that is Person->Roles and Role->Persons) yourself.

    Why are you having doubts that this is not the way to go?

    Regards

    Henrik
  3. DevCraft banner
  4. Daniel Plomp
    Daniel Plomp avatar
    130 posts
    Member since:
    Feb 2004

    Posted 02 Sep 2010 Link to this post

    Hi Hendrik,

    Yes, I guess this will be the right way. I first was thinking that with this approach I would actually add a new role, but I see how it works.
    Thanks for your reply.

    Regards,
    Daniel
Back to Top