Ian Muir
Ian Muir

Reputation: 911

Entity Framework 4 Code First, Complex Many to Many relationship

I've seen several examples of many to many relationships in EF using code-first, but I've run into a situation that I'm not sure how to solve.

My app has three POCO classes, Account, User and Role. Every user can be a member of multiple accounts and has a unique role for each one. For example, User A can be in Role A for Account A and Role B for Account B. Essentially, there is a many to many relationship between accounts and users, and each of these relationships also has a role that is assigned to each account-user combination.

In my current, non code-first setup. I have a table that has a user id, account id and role id.

Is there a way to do this using code-first?

Upvotes: 0

Views: 552

Answers (1)

Alexandre Brisebois
Alexandre Brisebois

Reputation: 6743

yes you can do this with CodeFirst you will need an extra class (entity) to represent this relationship table.

where your user will have a collection of account memberships which have a role and an account.

User
--- has a collection of AccountMemberShips

AccountMemberShip
--- has a  Role
--- has an Account
--- has a  User

Account
--- has a collection of AccountMemberShips

Role
--- has a collection of AccountMemberShips

Upvotes: 1

Related Questions