Lately, I have started with creating video tutorials for ASP.NET. Thus, today it is time to deep dive in the ASP.NET once again, following the Microsoft tutorial for ASP.NET MVC Web App from here.
In the video below, the following points are presented:
- Create an ASP.NET Core MVC web app
- Set up the site style
- Learn about EF Core NuGet packages
- Create the data model
- Create the database context
- Register the context for dependency injection
- Initialize the database with test data
- Create a controller and views
- View the database
In the video, there were 2 intesting moments, when the DB was not initialized correctly – once because of a missing line in the Startup.cs file and one, because the AutoId of one of the classes was overridden without informing the Entity Framework (EF) properly.
This is how the SchoolContext.cs class informs the EF how to name specific tables in the database upon creation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using ContosoUniversity.Models; using Microsoft.EntityFrameworkCore; namespace ContosoUniversity.Data { public class SchoolContext : DbContext { public SchoolContext(DbContextOptions<SchoolContext> options):base(options) { } public DbSet <Course> Courses { get; set; } public DbSet <Enrollment> Enrollments { get; set; } public DbSet <Student> Students { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Course>().ToTable("Cursos"); modelBuilder.Entity<Enrollment>().ToTable("Inscriptiones"); modelBuilder.Entity<Student>().ToTable("Estudiantes"); } } } |
And this is how the Main method is modified:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System; using ContosoUniversity.Data; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace ContosoUniversity { public class Program { public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<SchoolContext>(); DbInitializer.Initialize(context); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "Error during seeding the database!"); } } host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } } |
Thus, it does the following on startup:
- Gets the db context from the dependency injection container;
- Seeds the data from the static DbInitializer.Initialize(context) method;
- Disposes correctly the cotext, after the seed method is ready, with the “magic” of using();
The rest of the code is in GitHub – https://github.com/Vitosh/ASP/tree/master/EFCoreAsp.NetMvcWebApp/ContosoUniversity001
Enjoy!