错误:违反了多重约束

时间:2013-08-21 07:26:34

标签: wpf entity-framework code-first

我在代码冷杉中有一个与自我关系的类。

 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。

ViewModel中的

 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);

0 个答案:

没有答案