当用户创建自己的帐户时,他应该获得默认角色“用户”,稍后我将编辑该用户并赋予他admin或其他角色。我应该如何处理这个问题。现在,我收到此错误:
SqlException:INSERT语句与FOREIGN KEY冲突 约束“ FK__Users__RoleId__38996AB5”。发生冲突 数据库“ DormWebApp”,表“ dbo.Roles”,列“ Id”。该声明 已终止。
我的代码示例
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
public Role()
{
}
}
public ActionResult Create(Models.User user)
{
var roleToAssign = rolesRepository.GetById(2);
Models.Role roleConverted = new Models.Role() { Id = roleToAssign.Id , Name = roleToAssign.Name };
user.RegisterOn = DateTime.Now;
user.Role = roleConverted;
user.RoleId = roleConverted.Id;
if (ModelState.IsValid)
{
if (userServices.ExistingEmailAddress(user.Email))
{
ModelState.AddModelError("Email", "This email address can not be used.");
}
if (userServices.ExistingUsername(user.Username))
{
ModelState.AddModelError("Email", "This username can not be used.");
}
if(!userServices.ExistingUsername(user.Username) && !userServices.ExistingEmailAddress(user.Email))
{
var dbModel = new Domain.Entities.User();
TryUpdateModel(dbModel);
userServices.AddUser(dbModel);
return RedirectToAction("Index");
}
return View(user);
}
return View(user);
public class User
{
public int Id { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string Username { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[EmailAddress]
public string Email { get; set; }
public int RoleId { get; set; }
public bool IsActive { get; set; }
public string RoleName { get; set; }
public virtual Role Role { get; set; }
public User()
{
}
}
答案 0 :(得分:0)
听起来像出于某种原因,您要分配给User对象的RoleId不在Roles表中。您应该调试该应用程序,在AddUser之前使用断点,并检查RoleId包含的内容,并检查Roles表中DB中是否存在有效值。
希望这会有所帮助!
答案 1 :(得分:0)
我认为您的问题是TryUpdateModel()
不知道您要分配给域实体的RoleId
,因为您的视图可能没有RoleId的任何值。将其添加到Models.User
不会将其添加到视图上下文中。
如果您调试应用程序,请检查以确保roleConverted.Id
实际上等于2。
构建完Domain对象之后,手动添加这些属性。
public ActionResult Create(Models.User user)
{
var roleToAssign = rolesRepository.GetById(2);
Models.Role roleConverted = new Models.Role() { Id = roleToAssign.Id , Name = roleToAssign.Name };
user.RegisterOn = DateTime.Now;
user.Role = roleConverted;
user.RoleId = roleConverted.Id;
if (ModelState.IsValid)
{
if (userServices.ExistingEmailAddress(user.Email))
{
ModelState.AddModelError("Email", "This email address can not be used.");
}
if (userServices.ExistingUsername(user.Username))
{
ModelState.AddModelError("Email", "This username can not be used.");
}
if(!userServices.ExistingUsername(user.Username) && !userServices.ExistingEmailAddress(user.Email))
{
var dbModel = new Domain.Entities.User();
TryUpdateModel(dbModel);
// try this here
dbModel.RoleId = roleConverted.Id;
// you might also need
dbModel.RegisterOn = DateTime.Now;
userServices.AddUser(dbModel);
return RedirectToAction("Index");
}
return View(user);
}
return View(user);
}