Created
July 18, 2021 20:46
-
-
Save manoj-choudhari-git/393b6133abc84c31d945755b4e6c5d8a to your computer and use it in GitHub Desktop.
.NET - Entity Framework Core Demo showing how EnsureCreated and EnsureDeleted methods work
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static async Task Main(string[] args) | |
{ | |
using (var context = BuildUniversityContext()) { | |
// To Delete Existing Database if it exists | |
await context.Database.EnsureDeletedAsync(); | |
// To Create a new database if it does not exist | |
await context.Database.EnsureCreatedAsync(); | |
} | |
// First Unit-of-Work showing Add operation | |
AddStudents(); | |
Console.WriteLine("---------------------------------------------"); | |
Console.WriteLine("With Interceptor...."); | |
await GetAllStudents(applyInterceptor: true); | |
Console.WriteLine("---------------------------------------------"); | |
Console.WriteLine("Without Interceptor...."); | |
await GetAllStudents(applyInterceptor: false); | |
Console.WriteLine("---------------------------------------------"); | |
} | |
static void AddStudents() | |
{ | |
using var context = BuildUniversityContext(); | |
context.Add( | |
new Student | |
{ | |
FirstName = "John", | |
LastName = "Doe", | |
Address = "4 Privet Drive", | |
}); | |
context.Add( | |
new Student | |
{ | |
FirstName = "Jane", | |
LastName = "Doe", | |
Address = "4 Privet Drive", | |
}); | |
context.SaveChanges(); | |
} | |
static async Task GetAllStudents(bool applyInterceptor) | |
{ | |
using var context = BuildUniversityContext(); | |
IList<Student> studentCollection = null; | |
if (applyInterceptor) | |
{ | |
studentCollection = await context.Students.TagWith("Apply OrderBy DESC").ToListAsync(); | |
} | |
else | |
{ | |
studentCollection = await context.Students.ToListAsync(); | |
} | |
Console.WriteLine("Printing List of Students"); | |
foreach(var student in studentCollection) | |
{ | |
Console.WriteLine(student); | |
} | |
} | |
static UniversityContext BuildUniversityContext() | |
{ | |
var dbContextBuilder = new DbContextOptionsBuilder<UniversityContext>(); | |
// HARDCODED - For this demo. | |
var connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=University; Integrated Security=True;"; | |
dbContextBuilder.UseSqlServer(connectionString); | |
return new UniversityContext(dbContextBuilder.Options); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment