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
You have two problems.
MembershipUser doesn't define a key, either implicitly or explicitly. You don't show the mapping code, but that's what the error says.MembershipUser anyway. (2) is the most important point here, since it makes (1) kind of irrelevant. You should never depend on the SQL Provider DB tables. Nor should you use MembershipUser as an entity, since you don't control it, and the people who do maintain it don't intend for it to be used that way.
Get your membership data from the Membership API, not by hitting the DB directly via the EF.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With