Hi, i am just getting started with ASP.NET MVC and i'm using NHibernate for my data context. I have kept the foreign key fields in my entity classes so that it could hopefully making working with drop down lists easier but this is not the case.
Here is my post back action:
var user = userRepository.GetById(id);
if (!TryUpdateModel(user, "User", new[] { "UserName", "RoleID" }))
return View(user);
// Update the role
user.Role = roleRepository.GetById(user.RoleID);
This allows me to put my validation logic on the User.RoleID property.
Everything works fine until it saves it. Here's my user and mapping class:
public virtual int UserID { get; set; }
[Required(ErrorMessage = "Username is required")]
public virtual string UserName { get; set; }
[Required(ErrorMessage = "Role is required")]
public virtual int RoleID { get; set; }
public virtual Role Role { get; set; }
public UserMap()
{
Table("Users");
Id(x => x.UserID);
Map(x => x.UserName);
Map(x => x.RoleID);
References(x => x.Role, "RoleID");
}
However this throws back an error when it trys to commit the changes. I tried removing Map(x => x.RoleID); from the above mapping and the insert went through successfully but then the data was not populated when displaying the user.
My preferred solution would be to remove the RoleID property from the User entity (as recommended by NHibernate) but then i would have to handle my validation logic myself.
I'd appreciate it if someone could help. Thanks