下面的代码片段显示了我的场景:
[Table("User")]
public partial class UserModel
{
public UserModel()
{
UserRole = new HashSet<UserRoleModel>();
}
public int UserID { get; set; }
public string FullName { get; set; }
public virtual ICollection<UserRoleModel> UserRole { get; set; }
}
[Table("UserRole")]
public partial class UserRoleModel
{
public UserRoleModel()
{
User = new HashSet<UserModel>();
}
public int RoleID { get; set; }
public string RoleName { get; set; }
public virtual ICollection<UserModel> User { get; set; }
}
现在在OnModelCreating(DbModelBuilder modelBuilder)
EF中生成如下代码
modelBuilder.Entity<UserModel>()
.HasMany(e => e.UserRole)
.WithMany(e => e.User)
.Map(m => m.ToTable("UserRoleMapping").MapLeftKey("UserID").MapRightKey("UserRoleID"));
现在这很好将数据添加/插入UserRoleMapping
到表中。但是如何
从 UserRoleMapping 表中获取/更新数据?
我尝试在create-code-first-many-to-many帖子之后解决这个问题,并提出第三类join entity
public partial class UserRoleMappingModel
{
[Key, Column(Order = 0)]
public Guid UserId { get; set; }
public UserModel User { get; set; }
[Key, Column(Order = 1)]
public int RoleId { get; set; }
public UserRoleModel UserRole { get; set; }
}
然后添加public virtual ICollection<UserRoleMappingModel> UserRoleMapping { get; set; }
和UserModel
类UserRoleModel
但是当我尝试使用下面的代码从数据库中获取值时
var results = _userRepository.GetAll()
.Include(r => r.UserRoleMapping
.Select(s => s.UserRole))
.SingleOrDefault(e => e.ID == id);
它抛出错误
"执行命令定义时出错。有关详细信息,请参阅内部异常。System.Data.SqlClient.SqlException (0x80131904): 对象名称 'dbo.UserRoleMappingModel' 无效。\r\n
即使我尝试了以下配置OnModelCreating
,但没有按预期工作
modelBuilder.Entity<UserRoleMappingModel>()
.HasKey(e => new { e.UserId, e.RoleId });