2011-11-29 63 views
2

在使用SubmitChanges()之前,有沒有辦法在插入具有InsertOnSubmit()函數的行時檢查數據庫的約束?InsertOnSubmit約束

原因,我在循環一個csv文件生成的Datatable。我一次插入1行以顯示進度。現在,當發生衝突時,linq回滾所有更改,同時我希望插入成功插入。

現在,當運行此代碼時,它會在第一次衝突時發生錯誤並停止。在下一次運行此代碼時,它不會插入任何更多行和衝突覆蓋前的行。

我希望任何人都可以幫助我。下面你可以找到我的代碼片段。

問候,泰斯

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){} 
} 

回答

0

如何嘗試這樣的:

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集合中。然後,您可以繼續遍歷剩餘的配置文件,並在完成導入後,記錄或報告錯誤的配置文件,以便您可以更正它們並嘗試重新導入。