我是实体框架概念的新手。我为“用户列表”和角色创建模型,这些模型将确定那里受到尊重的访问。用户可以有多个角色,而角色可以有多个用户
public class TblUser
{
[Key]
[MaxLength(50)]
public string UserID { get; set; }
[MaxLength(35)]
public string UserName { get; set; }
[MaxLength(150)]
public string EMailAddress { get; set; }
[MaxLength(150)]
public string Password { get; set; }
public DateTime LastLogIn { get; set; }
[MaxLength(3)]
public string ResetPassword { get; set; }
[MaxLength(150)]
public string ResetNewPassword { get; set; }
public DateTime ResetPasswordExpire { get; set; }
[MaxLength(3)]
public string Active { get; set; }
public List<TblRole> Roles { get; set; }
}
public class TblRole
{
[Key]
[MaxLength(50)]
public string RoleID { get; set; }
[MaxLength(50)]
public string RoleName { get; set; }
public List<TblUser> Users { get; set; }
}
我现在正在尝试使用以下代码添加新用户,但出现此错误 {“约束失败\ r \ n唯一约束失败:TblRole.RoleID”}
public string addNewUser(string Username, string Email, Model.DB.TblRole roles)
{
using (DatabaseContext db = new DatabaseContext())
{
ExpenseMonitoringSystem.Controller.Security sec = new Security();
string randomPassword = sec.Encrypt(RandomString(6, false));
if((from user in db.TblUser where user.UserName==Username select user).FirstOrDefault()!=null)
throw new Exception("The username is already used");
if ((from user in db.TblUser where user.EMailAddress == Email select user).FirstOrDefault() != null)
throw new Exception("The email is already used");
var newuser = new ExpenseMonitoringSystem.Model.DB.TblUser
{
UserID = Guid.NewGuid().ToString(),
Password = randomPassword,
UserName = Username,
ResetPassword = "YES",
ResetNewPassword = randomPassword,
ResetPasswordExpire = DateTime.Now.AddDays(10),
EMailAddress = Email,
Active = "YES",
Roles = new List<Model.DB.TblRole>() { roles }
};
db.TblUser.Add(newuser);
db.SaveChanges();
return randomPassword;
}
}
答案 0 :(得分:2)
约束失败\ r \ n唯一约束失败:TblRole.RoleID
可能意味着您正在尝试向数据库中添加TblRole
,但是已经有一个具有相同RoleID
的现有记录。
查看您的代码,好像您将roles
放在某个地方,然后创建了DatabaseContext
,db
的新实例。问题是,db
在您调用roles
时认为db.TblUser.Add(newuser)
是新记录。要告诉db
数据库中已经存在roles
,可以在添加db.TblRole.Attach
之前在TblRole
中的每个roles
上调用newUser
。>
答案 1 :(得分:0)
使用Fluent API配置多对多关系
您可以了解有关实体关系here
的更多信息