Getting a weird error after I’ve tried to extend the MVC Membership provider in my code-first MVC3 project.
The errors are:
EntityType 'MembershipUser' has no key defined. Define the key for this EntityType.
EntitySet "MembershipUsers" is based on type "MembershipUser" that has no keys defined
I have set up the standard asp.net membership, but added an extra table & model called UserDetails, where the foreign key is the UserId field in aspnet_Users.
Once the entry has been inserted in to the users table, I get the UserId and try to enter the other details in the Useretails table, but that is when these errors appear. Here is the other relevant code. The AccountController:
if (createStatus == MembershipCreateStatus.Success)
{
//Add other user details
UserRepository _user = new UserRepository();
UserDetails userDetails = new UserDetails();
userDetails.EmployeeNumber = Request.Form["EmployeeNumber"];
userDetails.Title = Request.Form["Title"];
userDetails.FirstName = Request.Form["FirstName"];
userDetails.Initials = Request.Form["Initials"];
userDetails.Surname = Request.Form["Surname"];
userDetails.Nino = Request.Form["Nino"];
_user.AddUserDetails(userDetails, model.Email);
return RedirectToAction("Welcome", "Home");
}
UserRepository:
public MembershipUser GetUserByEmail(string email)
{
MembershipUser user = Membership.GetUser(email);
return user;
}
public void AddUserDetails(UserDetails userDetails, string email)
{
MembershipUser user = GetUserByEmail(email);
Guid userGuid = (Guid)Membership.GetUser(email).ProviderUserKey;
userDetails.UserID = userGuid; //Add UserID foreign key
using (IntranetApplication db = new IntranetApplication())
{
db.UserDetails.Add(userDetails);
db.SaveChanges();
}
}
The error fires on the db.SaveChanges line.
As MemberShip user is a class itself and not part of entity framework, does anyone know how I can set UserID as a primary key? I’ve checked in the database and it is already set, so don’t know how i can amend it in the code.
Thanks – any help appreciated
To expand on what Craig is saying, I know it’s convenient to link against the membership tables, but it’s not necessary. Write your queries to accept the user id field as a parameter, then pass it from the Membership.GetUser().ProviderUserKey.
Also, don’t be tempted to key your tables on UserName, as that can create a security problem if one user creates a user with a specific name, then is deleted, then a new user with the same name is created.