Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 添加多个对象时保存更改时出现主键异常_C#_Linq_Entity Framework - Fatal编程技术网

C# 添加多个对象时保存更改时出现主键异常

C# 添加多个对象时保存更改时出现主键异常,c#,linq,entity-framework,C#,Linq,Entity Framework,我有一个实体对象类型的对象列表 我正在使用ms sql server 2008 我写了一段代码如下: foreach (some_entity_obj obj_to_handle in this.some_entity_obj_list) { try { db.some_entity_obj.AddObject(obj_to_handle); if (dbsaveCounter % 10 == 0) { db.SaveChanges();

我有一个实体对象类型的对象列表 我正在使用ms sql server 2008

我写了一段代码如下:

foreach (some_entity_obj obj_to_handle in this.some_entity_obj_list)
{
  try
  {
    db.some_entity_obj.AddObject(obj_to_handle);

    if (dbsaveCounter % 10 == 0)
    {
        db.SaveChanges();

        this.monitor.SyncValues(some_monitoring_unit, another_monitoring_unit);
        some_monitoring_unit = 0;
        another_monitoring_unit = 0;

    }
    if (obj_to_handle.some_monitoring_unit != null)
        some_monitoring_unit += (double)obj_to_handle.some_monitoring_unit;
    if (obj_to_handle.another_monitoring_unit != null)
        another_monitoring_unit += (double)obj_to_handle.another_monitoring_unit;

    dbsaveCounter++;
  }
  catch (Exception ex)
  {
    this.monitor.PushToUnsecceeded_rows(obj_to_handle,ex);
    this.monitor.PushToErrors("Error in ** : ", ex, false);
  }
}
db.SaveChanges();
this.monitor.SyncValues(some_monitoring_unit, another_monitoring_unit);
我得到以下例外情况: 无法确定“实体对象”关系的主体端。多个添加的实体可能具有相同的主键

如果我每次运行循环时都保存更改,它就会工作

以下是我问题的简短版本:

为什么这样做有效:

foreach (foo _entObj in someList)
{
   db.foo.AddObject(_entObj);
   db.SaveChanges();
}
这是行不通的:

 int cnt = 0;
    foreach (foo _entObj in someList)
    {
       db.foo.AddObject(_entObj);
       if (cnt%10 == 0)
          db.SaveChanges();
       cnt++;
    }
    db.SaveChanges();

错误可能是由无法解析的外键ID(与引用相反)引起的。是否为在SQL数据库中使用外键的“some_entity_obj”的任何属性(列)分配了正确的值?所有值都是正确的。。如果不每隔10个循环保存一次更改(取消该if语句),则工作正常。只有一个主键(标识自动增量)可以在整个模型(要复制的相关部分)中编辑,它可能是相关的。