我想在注册时使用 MVC 中的 EF 模型与多对多关系添加多个角色
I want to Add multiple Roles at the time of registeration with many to many relationship using EF Models in MVC
我有角色的用户注册 table,我想通过多对多 Ef 模型生成的模型注册具有多个角色的新用户。
我在注册用户时遇到问题,新角色被插入到角色 table 中,然后这些新添加的角色被插入到 user_has_roles(交汇点)table。
这是注册表图片
这是数据库多对多关系 Tables Image
这是 EF 模型 Table 图片
我正在分享一些我写的代码
自动生成的模型类
user.cs
public partial class user
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public user()
{
this.user_role = new HashSet<user_role>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int user_id { get; set; }
public string user_email { get; set; }
public string user_full_name { get; set; }
public string user_password { get; set; }
public string user_phone { get; set; }
public string user_mobile { get; set; }
public Nullable<int> country_id { get; set; }
public Nullable<int> city_id { get; set; }
public virtual city city { get; set; }
public virtual country country { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<user_role> user_role { get; set; }
}
user_role.cs
public partial class user_role
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public user_role()
{
this.users = new HashSet<user>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int user_role_id { get; set; }
public string user_role_name { get; set; }
public Nullable<int> user_role_status { get; set; }
public string user_role_description { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<user> users { get; set; }
}
这是我的数据库上下文 class(自动生成
AccountDb.cs
public partial class SaholatEntities : DbContext
{
public SaholatEntities()
: base("name=SaholatEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<city> cities { get; set; }
public virtual DbSet<country> countries { get; set; }
public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
public virtual DbSet<user> users { get; set; }
public virtual DbSet<user_role> user_role { get; set; }
public virtual int sp_alterdiagram(string diagramname, Nullable<int> owner_id, Nullable<int> version, byte[] definition)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
var versionParameter = version.HasValue ?
new ObjectParameter("version", version) :
new ObjectParameter("version", typeof(int));
var definitionParameter = definition != null ?
new ObjectParameter("definition", definition) :
new ObjectParameter("definition", typeof(byte[]));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_alterdiagram", diagramnameParameter, owner_idParameter, versionParameter, definitionParameter);
}
public virtual int sp_creatediagram(string diagramname, Nullable<int> owner_id, Nullable<int> version, byte[] definition)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
var versionParameter = version.HasValue ?
new ObjectParameter("version", version) :
new ObjectParameter("version", typeof(int));
var definitionParameter = definition != null ?
new ObjectParameter("definition", definition) :
new ObjectParameter("definition", typeof(byte[]));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_creatediagram", diagramnameParameter, owner_idParameter, versionParameter, definitionParameter);
}
public virtual int sp_dropdiagram(string diagramname, Nullable<int> owner_id)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_dropdiagram", diagramnameParameter, owner_idParameter);
}
public virtual ObjectResult<sp_helpdiagramdefinition_Result> sp_helpdiagramdefinition(string diagramname, Nullable<int> owner_id)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<sp_helpdiagramdefinition_Result>("sp_helpdiagramdefinition", diagramnameParameter, owner_idParameter);
}
public virtual ObjectResult<sp_helpdiagrams_Result> sp_helpdiagrams(string diagramname, Nullable<int> owner_id)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<sp_helpdiagrams_Result>("sp_helpdiagrams", diagramnameParameter, owner_idParameter);
}
public virtual int sp_renamediagram(string diagramname, Nullable<int> owner_id, string new_diagramname)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
var new_diagramnameParameter = new_diagramname != null ?
new ObjectParameter("new_diagramname", new_diagramname) :
new ObjectParameter("new_diagramname", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_renamediagram", diagramnameParameter, owner_idParameter, new_diagramnameParameter);
}
public virtual int sp_upgraddiagrams()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_upgraddiagrams");
}
}
这是我注册用户的控制器方法 (POST)
//post register
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(AccountVM obj)
{
if(ModelState.IsValid)
{
// insert Data into user variable array from obj viewmodel
var user = new user()
{
user_email = obj.user_email,
user_full_name = obj.user_full_name,
user_password = obj.user_password,
user_phone = obj.user_phone,
user_mobile = obj.user_mobile,
country_id = obj.country_id,
city_id = obj.city_id
};
var user_roles = new user_role();
AccountDb.users.Add(user);
// insert Data into user_has_role variable array from obj viewmodel
foreach(var item in obj.selectedRoleList)
{
user_roles.user_role_id = Convert.ToInt32(item);
user_roles.users.Add(new user() { user_id = obj.user_id });
user.user_role.Add(new user_role() { user_role_id = Convert.ToInt32(item) });
}
if (AccountDb.SaveChanges() > 0)
{
TempData["errorMsg"] = "save";
return RedirectToAction("Index");
}
else
{
TempData["errorMsg"] = "queryError";
ViewBag.country_id = new SelectList(AccountDb.countries, "country_id", "country_name");
AccountVM objRole = new AccountVM();
objRole.getRoleList = AccountDb.user_role.ToList();
return View(objRole);
}
}
else
{
TempData["errorMsg"] = "modelError";
ViewBag.country_id = new SelectList(AccountDb.countries, "country_id", "country_name");
AccountVM objRole = new AccountVM();
objRole.getRoleList = AccountDb.user_role.ToList();
return View(objRole);
}
}
我想注册具有多个角色的用户,并且角色已经由 multi-select 在角色 table select 中定义,请帮帮我
当我用 1 个角色注册用户时,新角色添加到角色 table 并且新添加的角色分配给用户(只有 role_id 添加到角色 table),并且如果我分配 2 个角色,那么 2 个将被添加到角色 table
已编辑
Image of Junction table after registration
Image of user_role table
试试这个。您不要将角色保存在 user_role table 中,而是将其保存在 user_has_role table 中。
var user = new user()
{
user_email = obj.user_email,
user_full_name = obj.user_full_name,
user_password = obj.user_password,
user_phone = obj.user_phone,
user_mobile = obj.user_mobile,
country_id = obj.country_id,
city_id = obj.city_id
};
AccountDb.users.Add(user);
AccountDb.SaveChanges(); // save the user so that you can get the user_id
// insert Data into user_has_role variable array from obj viewmodel
foreach(var item in obj.selectedRoleList)
{
var user_role = new user_has_role
{
user_role_id = Convert.ToInt32(item),
user_id = user.user_id
};
AccountDb.user_has_role.Add(user_role);
}
AccountDb.SaveChanges(); //save changes after all roles are assigned
我这样做解决了我的问题
//post register
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(AccountVM obj)
{
if(ModelState.IsValid)
{
// insert Data into user variable array from obj viewmodel
var user = new user()
{
user_email = obj.user_email,
user_full_name = obj.user_full_name,
user_password = obj.user_password,
user_phone = obj.user_phone,
user_mobile = obj.user_mobile,
country_id = obj.country_id,
city_id = obj.city_id
};
AccountDb.users.Add(user);
// insert Data into user_has_role variable array from obj viewmodel
foreach(var item in obj.selectedRoleList)
{
int id = Convert.ToInt32(item);
user_role _user_role = AccountDb.user_role.FirstOrDefault(r => r.user_role_id == id);
_user_role.users.Add(user);
user.user_role.Add(_user_role);
}
if (AccountDb.SaveChanges() > 0)
{
TempData["errorMsg"] = "save";
return RedirectToAction("Index");
}
else
{
TempData["errorMsg"] = "queryError";
ViewBag.country_id = new SelectList(AccountDb.countries, "country_id", "country_name");
AccountVM objRole = new AccountVM();
objRole.getRoleList = AccountDb.user_role.ToList();
return View(objRole);
}
}
else
{
TempData["errorMsg"] = "modelError";
ViewBag.country_id = new SelectList(AccountDb.countries, "country_id", "country_name");
AccountVM objRole = new AccountVM();
objRole.getRoleList = AccountDb.user_role.ToList();
return View(objRole);
}
}
我有角色的用户注册 table,我想通过多对多 Ef 模型生成的模型注册具有多个角色的新用户。
我在注册用户时遇到问题,新角色被插入到角色 table 中,然后这些新添加的角色被插入到 user_has_roles(交汇点)table。
这是注册表图片
这是数据库多对多关系 Tables Image
这是 EF 模型 Table 图片
我正在分享一些我写的代码
自动生成的模型类 user.cs
public partial class user
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public user()
{
this.user_role = new HashSet<user_role>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int user_id { get; set; }
public string user_email { get; set; }
public string user_full_name { get; set; }
public string user_password { get; set; }
public string user_phone { get; set; }
public string user_mobile { get; set; }
public Nullable<int> country_id { get; set; }
public Nullable<int> city_id { get; set; }
public virtual city city { get; set; }
public virtual country country { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<user_role> user_role { get; set; }
}
user_role.cs
public partial class user_role
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public user_role()
{
this.users = new HashSet<user>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int user_role_id { get; set; }
public string user_role_name { get; set; }
public Nullable<int> user_role_status { get; set; }
public string user_role_description { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<user> users { get; set; }
}
这是我的数据库上下文 class(自动生成
AccountDb.cs
public partial class SaholatEntities : DbContext
{
public SaholatEntities()
: base("name=SaholatEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<city> cities { get; set; }
public virtual DbSet<country> countries { get; set; }
public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
public virtual DbSet<user> users { get; set; }
public virtual DbSet<user_role> user_role { get; set; }
public virtual int sp_alterdiagram(string diagramname, Nullable<int> owner_id, Nullable<int> version, byte[] definition)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
var versionParameter = version.HasValue ?
new ObjectParameter("version", version) :
new ObjectParameter("version", typeof(int));
var definitionParameter = definition != null ?
new ObjectParameter("definition", definition) :
new ObjectParameter("definition", typeof(byte[]));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_alterdiagram", diagramnameParameter, owner_idParameter, versionParameter, definitionParameter);
}
public virtual int sp_creatediagram(string diagramname, Nullable<int> owner_id, Nullable<int> version, byte[] definition)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
var versionParameter = version.HasValue ?
new ObjectParameter("version", version) :
new ObjectParameter("version", typeof(int));
var definitionParameter = definition != null ?
new ObjectParameter("definition", definition) :
new ObjectParameter("definition", typeof(byte[]));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_creatediagram", diagramnameParameter, owner_idParameter, versionParameter, definitionParameter);
}
public virtual int sp_dropdiagram(string diagramname, Nullable<int> owner_id)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_dropdiagram", diagramnameParameter, owner_idParameter);
}
public virtual ObjectResult<sp_helpdiagramdefinition_Result> sp_helpdiagramdefinition(string diagramname, Nullable<int> owner_id)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<sp_helpdiagramdefinition_Result>("sp_helpdiagramdefinition", diagramnameParameter, owner_idParameter);
}
public virtual ObjectResult<sp_helpdiagrams_Result> sp_helpdiagrams(string diagramname, Nullable<int> owner_id)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<sp_helpdiagrams_Result>("sp_helpdiagrams", diagramnameParameter, owner_idParameter);
}
public virtual int sp_renamediagram(string diagramname, Nullable<int> owner_id, string new_diagramname)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
var new_diagramnameParameter = new_diagramname != null ?
new ObjectParameter("new_diagramname", new_diagramname) :
new ObjectParameter("new_diagramname", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_renamediagram", diagramnameParameter, owner_idParameter, new_diagramnameParameter);
}
public virtual int sp_upgraddiagrams()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_upgraddiagrams");
}
}
这是我注册用户的控制器方法 (POST)
//post register
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(AccountVM obj)
{
if(ModelState.IsValid)
{
// insert Data into user variable array from obj viewmodel
var user = new user()
{
user_email = obj.user_email,
user_full_name = obj.user_full_name,
user_password = obj.user_password,
user_phone = obj.user_phone,
user_mobile = obj.user_mobile,
country_id = obj.country_id,
city_id = obj.city_id
};
var user_roles = new user_role();
AccountDb.users.Add(user);
// insert Data into user_has_role variable array from obj viewmodel
foreach(var item in obj.selectedRoleList)
{
user_roles.user_role_id = Convert.ToInt32(item);
user_roles.users.Add(new user() { user_id = obj.user_id });
user.user_role.Add(new user_role() { user_role_id = Convert.ToInt32(item) });
}
if (AccountDb.SaveChanges() > 0)
{
TempData["errorMsg"] = "save";
return RedirectToAction("Index");
}
else
{
TempData["errorMsg"] = "queryError";
ViewBag.country_id = new SelectList(AccountDb.countries, "country_id", "country_name");
AccountVM objRole = new AccountVM();
objRole.getRoleList = AccountDb.user_role.ToList();
return View(objRole);
}
}
else
{
TempData["errorMsg"] = "modelError";
ViewBag.country_id = new SelectList(AccountDb.countries, "country_id", "country_name");
AccountVM objRole = new AccountVM();
objRole.getRoleList = AccountDb.user_role.ToList();
return View(objRole);
}
}
我想注册具有多个角色的用户,并且角色已经由 multi-select 在角色 table select 中定义,请帮帮我
当我用 1 个角色注册用户时,新角色添加到角色 table 并且新添加的角色分配给用户(只有 role_id 添加到角色 table),并且如果我分配 2 个角色,那么 2 个将被添加到角色 table
已编辑 Image of Junction table after registration
Image of user_role table
试试这个。您不要将角色保存在 user_role table 中,而是将其保存在 user_has_role table 中。
var user = new user()
{
user_email = obj.user_email,
user_full_name = obj.user_full_name,
user_password = obj.user_password,
user_phone = obj.user_phone,
user_mobile = obj.user_mobile,
country_id = obj.country_id,
city_id = obj.city_id
};
AccountDb.users.Add(user);
AccountDb.SaveChanges(); // save the user so that you can get the user_id
// insert Data into user_has_role variable array from obj viewmodel
foreach(var item in obj.selectedRoleList)
{
var user_role = new user_has_role
{
user_role_id = Convert.ToInt32(item),
user_id = user.user_id
};
AccountDb.user_has_role.Add(user_role);
}
AccountDb.SaveChanges(); //save changes after all roles are assigned
我这样做解决了我的问题
//post register
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(AccountVM obj)
{
if(ModelState.IsValid)
{
// insert Data into user variable array from obj viewmodel
var user = new user()
{
user_email = obj.user_email,
user_full_name = obj.user_full_name,
user_password = obj.user_password,
user_phone = obj.user_phone,
user_mobile = obj.user_mobile,
country_id = obj.country_id,
city_id = obj.city_id
};
AccountDb.users.Add(user);
// insert Data into user_has_role variable array from obj viewmodel
foreach(var item in obj.selectedRoleList)
{
int id = Convert.ToInt32(item);
user_role _user_role = AccountDb.user_role.FirstOrDefault(r => r.user_role_id == id);
_user_role.users.Add(user);
user.user_role.Add(_user_role);
}
if (AccountDb.SaveChanges() > 0)
{
TempData["errorMsg"] = "save";
return RedirectToAction("Index");
}
else
{
TempData["errorMsg"] = "queryError";
ViewBag.country_id = new SelectList(AccountDb.countries, "country_id", "country_name");
AccountVM objRole = new AccountVM();
objRole.getRoleList = AccountDb.user_role.ToList();
return View(objRole);
}
}
else
{
TempData["errorMsg"] = "modelError";
ViewBag.country_id = new SelectList(AccountDb.countries, "country_id", "country_name");
AccountVM objRole = new AccountVM();
objRole.getRoleList = AccountDb.user_role.ToList();
return View(objRole);
}
}