|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using FileContextCore_Tests.Data; |
| 6 | +using FileContextCore_Tests.Helper; |
| 7 | +using Microsoft.EntityFrameworkCore.Internal; |
| 8 | +using Microsoft.EntityFrameworkCore.Storage; |
| 9 | +using Xunit; |
| 10 | + |
| 11 | +namespace FileContextCore_Tests |
| 12 | +{ |
| 13 | + public class TransactionTests |
| 14 | + { |
| 15 | + [Fact] |
| 16 | + public void TransactionSuccess() |
| 17 | + { |
| 18 | + TestContext db = new TestContext("json", "default"); |
| 19 | + db.Entries.RemoveRange(db.Entries); |
| 20 | + db.SaveChanges(); |
| 21 | + |
| 22 | + Assert.Empty(db.Entries); |
| 23 | + |
| 24 | + using (IDbContextTransaction transaction = db.Database.BeginTransaction()) |
| 25 | + { |
| 26 | + try |
| 27 | + { |
| 28 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 29 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 30 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 31 | + db.SaveChanges(); |
| 32 | + |
| 33 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 34 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 35 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 36 | + db.SaveChanges(); |
| 37 | + |
| 38 | + transaction.Commit(); |
| 39 | + } |
| 40 | + catch (Exception ex) |
| 41 | + { |
| 42 | + transaction.Rollback(); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + Assert.Equal(6, db.Entries.Count()); |
| 47 | + } |
| 48 | + |
| 49 | + [Fact] |
| 50 | + public void TransactionFailureRollback() |
| 51 | + { |
| 52 | + TestContext db = new TestContext("json", "default"); |
| 53 | + db.Entries.RemoveRange(db.Entries); |
| 54 | + db.SaveChanges(); |
| 55 | + |
| 56 | + Assert.Empty(db.Entries); |
| 57 | + |
| 58 | + using (IDbContextTransaction transaction = db.Database.BeginTransaction()) |
| 59 | + { |
| 60 | + try |
| 61 | + { |
| 62 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 63 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 64 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 65 | + db.SaveChanges(); |
| 66 | + |
| 67 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 68 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 69 | + db.Entries.Add(ModelCreator.GenerateEntry()); |
| 70 | + db.SaveChanges(); |
| 71 | + |
| 72 | + throw new Exception("Should perform rollback"); |
| 73 | + |
| 74 | + transaction.Commit(); |
| 75 | + } |
| 76 | + catch (Exception ex) |
| 77 | + { |
| 78 | + transaction.Rollback(); |
| 79 | + db.SaveChanges(); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + Assert.Equal(6, db.Entries.Count()); |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments