I have these classes
public class UserRole
{
public int RoleId { get; set; }
public int UserId { get; set: }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}
[Table("User")]
public class User
{
public User()
{
UserRoles = new HashSet<UserRole>();
}
public int FirstName { get; set; }
public int UserId { get; set: }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
[Table("Role")]
public class Role
{
public Role()
{
UserRoles = new HashSet<UserRole>();
}
public int RoleId { get; set; }
public string RoleName { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
I am trying to do simple insert into the UserRole table
public class Run
{
DbContext context;
public Run()
{
context = new DbContext();
}
public void Validate(User user, int roleId)
{
InsertUserRole(user,roleId)
context.SaveChanges();
}
}
public void InsertUserRole(user targetUser, int roleId)
{
UserRole targetUserRole = targetUser.UserRoles
.Where(u => u.RoleId == roleId)
.FirstOrDefault();
if (targetUserRole == null)
{
targetUserRole = new UserRole();
targetUserRole.RoleId = roleId;
targetUserRole.UserId = targetUser.UserId;
context.UserRoles.Add(targetUserRole);
}
}
When I am trying to insert into UserRole table, I get an exception
Violation of Unique KEy 'UQ_Role_Name'.Cannot insert duplicate key in dbo.Role
I need to insert row into UserRole as the role does not exist for user, and the role is present in Role table.
Please let me know how I can insert into Userole table using Entity Framework context