在使用SubmitChanges()之前,有没有办法在使用InsertOnSubmit()函数插入行时检查数据库的约束?
原因是,我正在循环从csv文件生成的数据表。我一次插入一行以显示进度。现在,当发生冲突时,linq回滚所有更改,而我希望成功的插入保持插入状态。
现在,当运行这段代码时,它在第一个冲突时给出一个错误,然后就停止了。它不会再插入任何行,冲突之前的行将在我下次运行此代码时被覆盖。
我希望任何人能在这方面帮助我。下面你可以从我的代码中找到一段代码。
致敬,Thijs
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){}
}发布于 2011-11-30 23:01:52
试试这个怎么样:
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集合中。然后,您可以继续迭代其余的配置文件,并在它们完成导入后,记录或报告错误的配置文件,以便您可以更正它们并尝试重新导入。
https://stackoverflow.com/questions/8308754
复制相似问题