我有这些类
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; }
}
我正在尝试在UserRole
表中进行简单的插入
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);
}
}
当我试图插入UserRole
表时,我得到一个异常
违反唯一密钥"UQ_Role_Name"。无法在dbo中插入重复密钥。角色
我需要在UserRole
中插入行,因为用户不存在该角色,并且该角色存在于Role
表中。
请让我知道如何使用实体框架上下文插入Userole
表
我不确定是否有足够的关于实体/架构的信息来缩小问题的具体原因,但我确实想到了一些事情。
首先,您是如何为UserRole实体指定PK的?这应该通过实体中的属性或通过实体配置来完成:
public class UserRole
{
[Key, Column(Order=0), ForeignKey("User")]
public int UserId { get; set; }
[Key, Column(Order=1), ForeignKey("Role")]
public int RoleId { get; set; }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}
接下来,要添加新的UserRole,应该可以通过设置ID来完成,尽管通常我建议设置导航属性而不是ID。这样做的原因是,这验证了您正在传递的值,并且该实体应该被视为";完整的";(导航属性可用(。
对于InsertUserRole方法,有几个调整。您不需要加载现有的实体,一个简单的存在性检查就足够了,而且速度更快,然后加载相关的引用。这可以插入到UserRole数据库集,也可以添加到请求的用户:
public void InsertUserRole(int userId, int roleId)
{
var userRoleExists = context.UserRoles.Any(x => x.UserId == userId && x.RoleId == roleId);
if(userRoleExists) return;
var user = context.Users.Single(x => x.UserId == userId);
var role = context.Roles.Single(x => x.RoleId == roleId);
UserRole userRole = new UserRole
{
User = user,
Role = role
};
context.UserRoles.Add(userRole);
context.SaveChanges();
}
或者:
public void InsertUserRole(int userId, int roleId)
{
var user = context.Users
.Include(x => x.UserRoles)
.Single(x => x.UserId == userId);
if(user.UserRoles.Any(x => x.RoleId == roleId) return;
var role = context.Roles.Single(x => x.RoleId == roleId);
UserRole userRole = new UserRole
{
User = user,
Role = role
};
user.UserRoles.Add(userRole);
context.SaveChanges();
}