在使用Entity Framework為主從表添加數據,當一個表添加數據成功,另一個表添加數據失敗,這時候就需要用到事務回滾。
比如有以下關系的2張表。
客戶端使用TransactionScope類可以實現事務回滾。
class Program{static void Main(string[] args){try{using (TransactionScope ts = new TransactionScope()){using (CountryDetailsEntities db = new CountryDetailsEntities()){Country country = new Country();country.CountryName = "USA";db.Countries.Add(country);db.SaveChanges();if (country.CountryID > 0){int a = 0;int total = 10 / a;State state = new State();state.CountryID = country.CountryID;state.StateName = "NewYork";db.States.Add(state);db.SaveChanges();}}ts.Complete();}}catch (Exception ex){throw;}}}
以上,在添加State表數據的時候,模擬了一個異常,通過斷點調試執行完畢,發現數據庫中沒有增加任何數據。

