我在创建自我参考时遇到问题。
我有一个看起来像这样的课程
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。