【问题标题】:InsertOnSubmit constraintsInsertOnSubmit 约束
【发布时间】:2011-11-29 09:51:40
【问题描述】:

在使用SubmitChanges() 之前使用InsertOnSubmit() 函数插入行时,有没有办法检查数据库的约束?

原因,我正在循环从 csv 文件生成的数据表。我一次插入 1 行以显示进度。现在,当发生冲突时,linq 会回滚所有更改,而我希望成功的插入保持插入状态。

现在运行此代码时,它会在第一次冲突时出错,然后停止。它不会再插入任何行,并且在我下次运行此代码时会覆盖冲突之前的行。

我希望任何人都可以帮助我解决这个问题。下面你可以从我的代码中找到一个 sn-p。

问候,蒂斯

foreach (DataRow row in Data.Rows)
{
  ProfilePrefillData profile = new ProfilePrefillData();

  //Paramaters
  profile.ProfileId = new Guid(row["profileid"].ToString());
  ...

  //Insert & submit
  db.ProfilePrefillDatas.InsertOnSubmit(profile);

  try
  {
    db.SubmitChanges(ConflictMode.ContinueOnConflict);
  }
  catch (Exception ex){}
}

【问题讨论】:

    标签: c# .net sql database linq


    【解决方案1】:

    试试这个怎么样:

    List<ProfilePrefillData> badProfiles = new List<ProfilePrefillData>();
    foreach (DataRow row in Data.Rows)
    { 
      ..
    
      try 
      {
        db.SubmitChanges(ConflictMode.ContinueOnConflict);
      }
      catch (Exception ex)
      {
        // record which are the bad profiles
        badProfiles.Add(profile);
    
        // Remove the bad profile from items to be added
        db.ProfilePrefillDatas.Remove(profile);
      }
    }
    
    // Return some information to the user about the bad profiles so that
    // they can be identified, corrected and reimported.
    LogBadProfileData(badProfiles);
    

    因此,当配置文件导致错误时,您可以将其从 DataContext 的集合中删除(这样它就不会尝试在下一次迭代中重新插入它们)并将它们存储在 badProfiles 集合中。然后,您可以继续遍历剩余的配置文件,在它们完成导入后,记录或报告错误的配置文件,以便您可以更正它们并尝试重新导入。

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多