Reputation: 33
I am experiencing problems with adding users to roles within MVC 5. When I run the code block I get "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."
Then when I check the entity validation errors they aren't very helpful.
{System.Data.Entity.Validation.DbEntityValidationResult} is what I get.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RoleAddToUser(string UserName, string RoleName)
{
using (var context = new ApplicationDbContext())
{
//Gets the user details
ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
//Add the user to a role, using id ...
this.UserManager.AddToRole(user.Id, RoleName);
ViewBag.ResultMessage = "Role created successfully !";
// prepopulate roles for the view dropdown
var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = list;
return View("ManageUserRoles");
}
}
And this is the UserManager:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
I am really frustrated at this point as this is the first time I am working with roles in MVC, and so far it has not been a good experience.
I hope someone here can help me find a solution to my problem.
P.S. The code Im using is based off this tutorial: Working with Roles in ASP.NET Identity for MVC
This is the view:
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<p>
Username : @Html.TextBox("UserName")
Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")
</p>
<input type="submit" value="Save" />
This is the Default user class, with an added property:
public class ApplicationUser : IdentityUser
{
[Required]
[MaxLength(13)]
[MinLength(13)]
[Key]
public string IDNumber { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
EDIT:I Found the problem... Because EF uses names followed by ID as a default key, my Application kept confusing the UserID (which was a id number) with the Id field. Thanks for all the help.
Upvotes: 0
Views: 717
Reputation: 1102
Why don't you catch the exception DbEntityValidationResult
and check the validation errors?
There you can check which property is wrong and why. You can get this error if any of the data is not satisfying model attributes rules (for example the required constraint).
Try adding the following statement...
catch (DbEntityValidationException ex)
{
foreach (var errors in ex.EntityValidationErrors)
{
foreach (var error in errors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", error.PropertyName, error.ErrorMessage);
}
}
}
Upvotes: 1