static async Task RemoveDbAsync() { using (var ctx = new NameAgeContext()) { bool deleted = await ctx.Database.EnsureDeletedAsync(); string deletion = deleted ? "deleted" : "non-existence"; Console.WriteLine($"database deletion: {deletion}"); } }
static async Task NewDbAsync() { using (var ctx = new NameAgeContext()) { bool created = await ctx.Database.EnsureCreatedAsync(); string creation = created ? "created" : "exists"; Console.WriteLine($"database creation: {creation}"); } }
// await NewDbAsync();// 当表不存在的时候,可以重新建表。 // await RemoveDbAsync(); // alter table nameage drop constraint PK_NameAge // set IDENTITY_INSERT NameAge ON // await AddRecordAsync("efcore11", 23); // TODO, no record inserted. static async Task QueryUpdateDeleteBooks() { using (var ctx = new NameAgeContext()) { // tested List <NameAge> list = await ctx.DbRows.ToListAsync(); foreach (var na in list) { Console.WriteLine($"{na.NameAgeId}, {na.Name}, {na.Age}"); } Console.WriteLine(); // tested List <NameAge> list2 = await ctx.DbRows .Where(r => r.Name == "duke").ToListAsync(); foreach (var na in list2) { Console.WriteLine($"{na.NameAgeId}, {na.Name}, {na.Age}"); } // tested NameAge record = await ctx.DbRows .Where(r => r.Name == "selves").FirstOrDefaultAsync(); if (record != null) { record.Age += 1; // record.Name = "selves"; int c = await ctx.SaveChangesAsync(); // update statement Console.WriteLine($"{c} records updated"); } // tested var toRemove = await ctx.DbRows .Where(r => r.Name == "myname").ToListAsync(); ctx.DbRows?.RemoveRange(toRemove); int count = await ctx.SaveChangesAsync(); Console.WriteLine($"{count} records deleted"); } // QueryUpdateDeleteBooks(); }
public static async Task AddRecordAsync(string name, int age) { using (var ctx = new NameAgeContext()) { using (var tx = ctx.Database.BeginTransaction()) { // ctx.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.NameAge ON"); // ctx.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.NameAge OFF"); var nameAge = new NameAge { Name = name, Age = age }; /*await*/ ctx.DbRows?.Add(nameAge); int rows = await ctx.SaveChangesAsync(); // ctx.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.NameAge OFF"); Console.WriteLine($"{rows} row(s) inserted"); tx.Commit(); } } }