我在创建自引用时遇到了问题。
我有一个看起来像这样的课程
public class User
{
[MaxLength(50, ErrorMessage = "")]
[Required(ErrorMessage = "")]
public string FirstName { get; set; }
[MaxLength(50, ErrorMessage = "")]
[Required(ErrorMessage = "")]
public string LastName { get; set; }
[Key]
[Required(ErrorMessage = "")]
[MaxLength(20, ErrorMessage = "")]
public string UserName { get; set; }
[Required(ErrorMessage = "")]
[MaxLength(20, ErrorMessage = "")]
public string Password { get; set; }
[ForeignKey("ParentUser")]
public string ParentUserName { get; set; }
public User ParentUser { get; set; }
public ICollection<User> SubsetUsers { get; set; }
}
并使用Fluent API配置自引用关联:
modelBuilder.Entity<User>()
.HasOptional(a => a.ParentUser)
.WithMany(a=> a.SubsetUsers)
.HasForeignKey(a => a.ParentUserName);
当我编辑用户并想要选择用户(db.User.Find(SelectedUser.UserName)
)时,我收到错误:
违反了多重性约束。 “AutomationDataLayer.User_ParentUser”关系的“User_ParentUser_Target”角色具有多重性1或0..1。
答案 0 :(得分:0)
您需要处理双向映射:
modelBuilder.Entity<User>()
.HasMany(a => a.SubsetUsers)
.WithRequired(a => a.ParentUser)
.HasForeignKey(a => a.ParentUserName);
modelBuilder.Entity<User>()
.HasOptional(a => a.ParentUser)
.WithMany(a=> a.SubsetUsers);
答案 1 :(得分:0)
看看this question。如果我将问题应用到您的问题,那么同一个用户被多次添加到SubsetUsers集合。