欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#在Entity Framework中實(shí)現(xiàn)事務(wù)回滾

 更新時(shí)間:2022年08月27日 10:36:40   作者:Darren Ji  
這篇文章介紹了C#在Entity Framework中實(shí)現(xiàn)事務(wù)回滾的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

在使用Entity Framework為主從表添加數(shù)據(jù),當(dāng)一個(gè)表添加數(shù)據(jù)成功,另一個(gè)表添加數(shù)據(jù)失敗,這時(shí)候就需要用到事務(wù)回滾。

比如有以下關(guān)系的2張表。

客戶端使用TransactionScope類可以實(shí)現(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ù)的時(shí)候,模擬了一個(gè)異常,通過(guò)斷點(diǎn)調(diào)試執(zhí)行完畢,發(fā)現(xiàn)數(shù)據(jù)庫(kù)中沒(méi)有增加任何數(shù)據(jù)。

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接

相關(guān)文章

最新評(píng)論