私はユーザーと役割の間に多対多の関係を持っています。それらは次のように設定されます:
public partial class User
{
//public User()
//{
// //this.DateCreated = DateTime.Now; //set default value
// Roles = new HashSet<Role>();
//}
public ICollection<Role> Roles { get; set; } //many to many relationship
public int UserId { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string City { get; set; }
//foreign key
public int CountryId { get; set; }
//navigation properties
public virtual Country Country { get; set; }
//foreign key
public int LanguageId { get; set; }
//navigation properties
public virtual Language Language { get; set; }
public string EmailAddress { get; set; }
public long? FacebookId { get; set; }
public DateTime DateCreated { get; set; }
}
public partial class Role
{
//public Role()
//{
// Users = new HashSet<User>();
//}
public ICollection<User> Users { get; set; } //many to many relationship
public int RoleId { get; set; }
public string RoleName { get; set; }
}
//many to many relationship
modelBuilder.Entity<User>().
HasMany(c => c.Roles).
WithMany(p => p.Users).
Map(
m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UserRoles", schemaName: "Main");
});
新しいユーザーを追加するコードで、そのユーザーにロールを追加できるようにしたいと思います。ただし、これを行うと、新しいロールもロールテーブルに追加されます。これを行う正しい方法は何ですか?
[HttpPost]
public ActionResult UserAdd(UserDTO user)
{
if (ModelState.IsValid)
{
//do mapping manually here
Country country = _repository.GetCountryByCountryId(user.CountryId);
Language language = _repository.GetLanguageByLanguageId(user.LanguageId);
User entity = new User();
entity.FirstName = user.FirstName;
entity.Surname = user.Surname;
entity.Username = user.Username;
entity.Password = user.Password;
entity.City = user.City;
entity.CountryId = country.CountryId;
entity.LanguageId = language.LanguageId;
entity.Country = country;
entity.Language = language;
entity.EmailAddress = user.EmailAddress;
entity.FacebookId = null;
entity.DateCreated = DateTime.Now;
entity.Roles = new List<Role>();
foreach (int i in user.Roles)
{
Role role = _repository.GetRoleByRoleId(i);
entity.Roles.Add(new Role { RoleId = i, RoleName = role.RoleName });
}
int newUserId = _repository.AddUser(entity);
return View();
} }