C# InsertOnSubmit约束
在使用SubmitChanges之前,使用InsertOnSubmit函数插入行时,是否有方法检查数据库的约束 原因是,我正在循环从csv文件生成的数据表。我一次插入一行以显示进度。现在,当发生冲突时,linq将回滚所有更改,而我希望成功的插入保持插入状态 现在,当运行这段代码时,它在第一次冲突时给出一个错误,并在那里停止。它不会再插入任何行,冲突前的行将在下次运行此代码时被覆盖 我希望任何人都能在这方面帮助我。下面是我的代码片段 你好,ThijsC# InsertOnSubmit约束,c#,.net,sql,database,linq,C#,.net,Sql,Database,Linq,在使用SubmitChanges之前,使用InsertOnSubmit函数插入行时,是否有方法检查数据库的约束 原因是,我正在循环从csv文件生成的数据表。我一次插入一行以显示进度。现在,当发生冲突时,linq将回滚所有更改,而我希望成功的插入保持插入状态 现在,当运行这段代码时,它在第一次冲突时给出一个错误,并在那里停止。它不会再插入任何行,冲突前的行将在下次运行此代码时被覆盖 我希望任何人都能在这方面帮助我。下面是我的代码片段 你好,Thijs foreach (DataRow row in
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){}
}
试试这个怎么样:
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集合中。然后,您可以继续遍历其余的配置文件,在它们导入完成后,记录或报告错误的配置文件,以便您可以更正它们并尝试重新导入。尝试一下如何:
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集合中。然后,您可以继续遍历其余的配置文件,在它们完成导入后,记录或报告错误的配置文件,以便您可以更正它们并尝试重新导入