This is a migrated thread and some comments may be shown as answers.

Question about adding records in intermediate table

2 Answers 49 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Daniel Plomp
Top achievements
Rank 2
Daniel Plomp asked on 01 Sep 2010, 05:20 PM
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 Answers, 1 is accepted

Sort by
0
IT-Als
Top achievements
Rank 1
answered on 01 Sep 2010, 07:11 PM
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
0
Daniel Plomp
Top achievements
Rank 2
answered on 02 Sep 2010, 01:23 PM
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
Tags
General Discussions
Asked by
Daniel Plomp
Top achievements
Rank 2
Answers by
IT-Als
Top achievements
Rank 1
Daniel Plomp
Top achievements
Rank 2
Share this question
or