【问题标题】:DbUpdateException while saving entities , one to many relationships保存实体时出现 DbUpdateException,一对多关系
【发布时间】:2015-10-23 00:47:00
【问题描述】:

拥有一个包含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。

内部执行

“DepotRayon”关联集中的关系处于“已删除”状态。给定多重约束,相应的“人造丝”也必须处于“已删除”状态。

【问题讨论】:

  • 请发布 InnerException
  • 您是否在 Rayon 对象上设置 Depot 属性?您是在创建新的 Rayon 对象还是只是将它们与 Depot 相关联?如果您不尝试创建它们,它们是否附加到上下文中?
  • 抱歉耽搁了abhinav sharma

标签: c# entity-framework


【解决方案1】:

问题在于仓库的多重性必须为 (0.. 1),因为当我从仓库中移除人造丝时,人造丝实体中的外键变为空,这会导致异常

【讨论】:

    猜你喜欢
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    相关资源
    最近更新 更多