James
James

Reputation: 1188

ASP.NET MVC 3 with EF not recognizing the many to many join table

In my database I have a User table and then another table with something like roles. There is a many to many join table between them. When someone is making a new user they have to be able to select the role they want for the user. However EF is not letting me associate my user with this other table. I had a dropdown list, but when the role was selected an invalid enrty error came up saying the PKID was not the correct input. I must be missing something in how EF works, or at least how it links to MVC 3

Upvotes: 0

Views: 552

Answers (1)

delete
delete

Reputation:

Generally speaking, when you have a many to many relationship you need a separate table to hold the two foreign keys.

So you might have:

User
------
ID
Name


Role
------
ID
Name


UserRoles
------
ID
UserID
RoleID

Why do you need a many to many relationship here? If I were you I'd create something like

User
------
ID
Name
IDRoleType


Role
------
ID
RoleType

That way a user can have a role, and in your code you can do something like:

public IQueryable FindUsers()
{
    MyEntities db = new MyEntities();
    return db.Users.Where(u => u.IDRoleType == 0);
}

Or

public IQueryable FindUsers()
{
    MyEntities db = new MyEntities();
    return db.Users.Where(u => u.Role.RoleType == "Admin");
}

Upvotes: 1

Related Questions