保存实体时的DbUpdateException,一对多关系

本文关键字:一对多 关系 DbUpdateException 实体 保存 | 更新日期: 2023-09-27 18:05:40

有一个具有DepotRayon实体的实体模型,使得每个Rayon必须与一个Depot相关联,每个Depot可以与零个或多个Rayon相关联。

人造纤维(0..*)<------->(1)仓库

下面是我的代码:
public void Update(Depot obj)
{
  var testDepot = DepotContainer.DepotSet.FirstOrDefault(c => c.Id == obj.Id);
  testDepot.Nom = obj.Nom;
  testDepot.Zone = obj.Zone;
  testDepot.Rayons = obj.Rayons;
  DepotContainer.SaveChanges();
}

仓库

public partial class Depot
{
 public Depot() { this.Rayons = new HashSet<Rayon>(); }
 public int Id { get; set; }
 public string Nom { get; set; }
 public string Zone { get; set; }
 public virtual ICollection<Rayon> Rayons { get; set; }
}

人造丝

public partial class Rayon
{
 public Rayon() { this.Article = new HashSet<Article>(); }
 public int Id { get; set; }
 public string Code { get; set; }
 public string Description { get; set; }
 public virtual Depot Depot { get; set; }
 public virtual ICollection<Article> Article { get; set; }
}

当保存更改时,我得到了这些错误:

附加信息:保存未公开其关系的外键属性的实体时发生错误。EntityEntries属性将返回null,因为不能将单个实体标识为异常的来源。通过在实体类型中公开外键属性,可以更容易地在保存时处理异常。详情请参见InnerException。

内部Execption

来自'DepotRayon' AssociationSet的关系处于'Deleted'状态。考虑到多重约束,相应的"Rayon"也必须处于"Deleted"状态。

保存实体时的DbUpdateException,一对多关系

问题是仓库的多重数必须是(0..)1)因为当我从仓库中删除人造丝时,人造丝实体中的外键变为null,这使得

异常