C#在Entity Framework中實現(xiàn)事務(wù)回滾
在使用Entity Framework為主從表添加數(shù)據(jù),當(dāng)一個表添加數(shù)據(jù)成功,另一個表添加數(shù)據(jù)失敗,這時候就需要用到事務(wù)回滾。
比如有以下關(guān)系的2張表。

客戶端使用TransactionScope類可以實現(xiàn)事務(wù)回滾。
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表數(shù)據(jù)的時候,模擬了一個異常,通過斷點調(diào)試執(zhí)行完畢,發(fā)現(xiàn)數(shù)據(jù)庫中沒有增加任何數(shù)據(jù)。
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
C# TextBox控件實現(xiàn)只能輸入數(shù)字的方法
這篇文章主要介紹了C# TextBox控件實現(xiàn)只能輸入數(shù)字的方法,本文使用TextBox的keypress事件實現(xiàn)這個需求,需要的朋友可以參考下2015-06-06

