/// <summary> /// https://docs.microsoft.com/en-us/ef/core/saving/transactions /// </summary> static void Transactions() { using (var db = new NWContext()) { var tran = db.Database.BeginTransaction(); try { // Acciones tran.Commit(); } catch (Exception) { tran.Rollback(); throw; } } using (var ts = new TransactionScope()) { using (var db = new NWContext()) { // CRUD actions db.SaveChanges(); } ts.Complete(); } }
private static void CRUD() { using (var db = new NWContext()) { int lastId = db.Products.Max(p => p.ProductId); var np = new Product() { ProductName = $"Demostración #{++lastId}", Discontinued = false }; db.Products.Add(np); db.SaveChanges(); np.ProductName += " ACTUALIZADO"; foreach (var e in db.ChangeTracker.Entries <Product>()) { Console.WriteLine($"{e.Property("ProductName").CurrentValue} {e.State}"); } db.SaveChanges(); db.Products.Remove(np); db.SaveChanges(); foreach (var p in db.Products.Include(p => p.Category)) { Console.WriteLine($"{p.ProductId}, {p.ProductName}, {p.UnitPrice}, {p.Category?.CategoryName ?? "Sin categorÃa"}"); } Console.WriteLine($"Total de productos: {db.Products.Count()}"); Console.ReadLine(); } }