0

我在代码中有一个 Class 与 self 的关系。

 public class OrganizationalUnit
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "")]
    [MaxLength(100, ErrorMessage = "")]
    public string Name { get; set; }

    [ForeignKey("Type")]
    [Required(ErrorMessage = "")]
    public int TypeId { get; set; }
    public virtual Type Type { get; set; }

    [ForeignKey("Parent")]
    public int? ParentId { get; set; }
    public virtual OrganizationalUnit ParentUnit { get; set; }}

    public  ICollection<OrganizationalUnit> OrganizationalSubUnits { get; set; }

当我想编辑一个 OrganizationalUnit 项目时,我收到错误

违反了多重性约束。关系“AutomationDataEntryModel.OrganizationalUnit_Parent”的角色“OrganizationalUnit_Parent_Target”具有多重性 1 或 0..1。

在视图模型中

 OrganizationalUnit unit = db.OrganizationalUnit.Find(SelectedOrganizationalUnit.Id);
 unit.Name = Name;
 unit.TypeId =Type;
 unit.ParentId = ParentOrganizationalUnit;

 db.SaveChanges();

编辑

我为此使用流利的 API

 modelBuilder.Entity<OrganizationalUnit>()
   .HasOptional(a => a.ParentOrganizationalUnit)
   .WithMany(a => a.OrganizationalSubUnits)
   .HasForeignKey(a => a.ParentOrganizationalUnitId);
4

0 回答 0