EF多个添加的实体可能具有相同的主键错误

时间:2016-06-08 12:58:05

标签: c# entity-framework ef-code-first

我要创建一个新的级联 [node] --1:many-- [currency] --1:many-- [unit] 使用EF 6.x定义代码优先:

public class CashFlowSpendableMinimumNode {
  ...
  [ForeignKey("CashFlowSpendableMinimumNodeId")]
  public ICollection<CashFlowSpendableMinimumCurrency> CashFlowSpendableMinimumCurrencies { get; private set; }
  ...
}
public class CashFlowSpendableMinimumCurrency {
  ...
  public int CashFlowSpendableMinimumNodeId { get; set; }
  [ForeignKey("CashFlowSpendableMinimumNodeId")]
  public CashFlowSpendableMinimumNode CashFlowSpendableMinimumNode { get; set; 
  ...
  [ForeignKey("CashFlowSpendableMinimumCurrencyId")]
  public ICollection<CashFlowSpendableMinimumUnit> CashFlowSpendableMinimumUnits { get; set; }
  ...
}

public class CashFlowSpendableMinimumUnit {
  ...
  public int CashFlowSpendableMinimumCurrencyId { get; set; }
  [ForeignKey("CashFlowSpendableMinimumCurrencyId")]
  public CashFlowSpendableMinimumCurrency CashFlowSpendableMinimumCurrency { get; set; }
  ...
}

第一部分即节点 - 货币之间的关系按预期工作:我创建一个新的货币实例并将其添加到 DbSet&lt; CashFlowSpendableMinimumCurrency&gt; - &gt;它出现在导航属性(集合) nodeMinimum.CashFlowSpendableMinimumCurrencies 中,当关系保存到DB时,它的Id被正确解析。

第二种关系货币 - 单位不起作用,即使我尝试以与节点 - 货币之间的第一种关系相同的方式定义它:当我创建时新的单元实例并将其添加到导航属性 currMinimum.CashFlowSpendableMinimumUnits 中的 DbSet&lt; CashFlowSpendableMinimumUnit&gt; 不会出现,如果我继续执行,通过稍后调用 SaveChanges()来尝试使级联持久化会导致%subject%中的错误。

更新1

我省略了错误信息的确切措辞,这里是:

无法确定&#39; xxx.yyy.Database.CashFlowSpendableMinimumNode_CashFlowSpendableMinimumCurrencies&#39;的主要结尾。关系。多个添加的实体可能具有相同的主键。

更新2

我发现,使其运行的唯一解决方案是过早冲洗变更跟踪器:

foreach (var node in nodes)
{
   nodeMinimum = new ...
   DbSet<CashFlowSpendableMinimumNode>.Add(nodeMinimum);
   foreach (var curr in currencies)
   {
      currMinimum = new ...
      DbSet<CashFlowSpendableMinimumCurrency>.Add(currMinimum);

      DbContext.SaveChanges();  //The premature flush to fix a problem

      foreach (var unit in units)
      {
         unitMinimum = new ...
         DbSet<CashFlowSpendableMinimumUnit>.Add(unitMinimum);
      }
   }
}
DbContext.SaveChanges();
...

更新3

关于讨论的构造函数和实例创建:

public CashFlowSpendableMinimumCurrency()
{
  CashFlowSpendableMinimumUnits = new List<CashFlowSpendableMinimumUnit>();
}

[...]
CashFlowSpendableMinimumCurrency result = new CashFlowSpendableMinimumCurrency()
{
  CurrencyCode = ACurrencyCode,  // the attached entity
  Curr = ACurrencyCode.Curr,     // string
  Minimum = minimum,  //decimal
  Median = median,  //decimal
  CashFlowSpendableMinimumNode = ANodeMinimum,  // parent in 1:n relation, EntityState.Added
  ExchangeRate = 1, //decimal
  DeclaredExchangeRate = false,
  BanknotesContribution = 0, //double
  BanknotesSpendableMinimum = 0, //decimal
  CoinsContribution = 0, //double
  CoinsSpendableMinimum = 0, //decimal
};
ADbContext.CashFlowSpendableMinimumCurrencies.Add(result);

拜托,有没有人看到,出了什么问题?

谢谢,pf

0 个答案:

没有答案