Follow this guide to create a new ASP.NET MVC project using VSCode. We'll also use the ASPNET CodeGenerator package and configure the Entity Framework to use MySQL.
Open your terminal and create a new directory for your project. Navigate into it and run the following command to create a new ASP.NET MVC project:
dotnet new mvc -o NameOfMyProject
dotnet dev-certs https --trust
Add the NuGet package for Entity Framework Core MySQL provider.
dotnet tool uninstall --global dotnet-ef
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design --version 7.0.3
dotnet add package Microsoft.EntityFrameworkCore.SQLite --version 7.0.11
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design --version 7.0.10
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 7.0.11
dotnet add package Microsoft.EntityFrameworkCore.Tools --version 7.0.11
dotnet add package MySql.EntityFrameworkCore --version 7.0.2
Install the ASPNET CodeGenerator package:
dotnet tool uninstall --global dotnet-aspnet-codegenerator
dotnet tool install --global dotnet-aspnet-codegenerator
Create your model classes in the Models
folder, using the code generator:
dotnet aspnet-codegenerator model -n Department -o Models
Create a new folder called Data. In the folder create a new file called ApplicationDbContext.cs. Add the following to the file:
using Microsoft.EntityFrameworkCore;
namespace WorldDominion.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
// Change to be your model(s) and table(s)
public DbSet<ModelName> TableName { get; set; }
}
}
In the Program.cs file, add the following line, after the "// Add services to the container." comment:
// Add MySQL
var connectionString = builder.Configuration.GetConnectionString("Default") ?? throw new InvalidOperationException("Connection string not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySQL(connectionString));
Using the terminal, run the following command to scaffold controllers and views:
dotnet aspnet-codegenerator controller -name [ControllerName] -m [ModelName] -dc [DbContextName] --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries
Replace [ControllerName]
, [ModelName]
, and [DbContextName]
with appropriate names.
Initialize a new migration:
dotnet ef migrations add InitialMigration
Apply the migration to the database:
dotnet ef database update
Run your project to make sure everything works:
dotnet run
Adding Authentication and Authorization to an existing MVC project in ASP.NET Core involves several steps. Below is a simplified step-by-step guide to achieve this, assuming you're using ASP.NET Core Identity for authentication and authorization:
- Install Necessary Packages:
- Ensure you have the necessary NuGet packages installed for ASP.NET Core Identity.
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore --version 7.0.13
dotnet add package Microsoft.AspNetCore.Identity.UI --version 7.0.13
- Update Program.cs:
- Register the identity services and the
ApplicationDbContext
in theConfigureServices
method. - Ensure authentication and authorization middleware are added in the
Configure
method.
- Register the identity services and the
// Adding identity service and roles
builder.Services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
// Setup authentication and authorization
app.UseAuthentication();
app.UseAuthorization();
- Update DbContext:
- Ensure your
ApplicationDbContext
class extendsIdentityDbContext
.
- Ensure your
public class ApplicationDbContext : IdentityDbContext<IdentityUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Department> Departments { get; set; }
public DbSet<Product> Products { get; set; }
}
- Scaffold the Views
dotnet aspnet-codegenerator identity -dc WorldDominion.Models.ApplicationDbContext --files "Account.Register;Account.Login;Account.Logout"
- Register Razor Pages Middleware
app.MapRazorPages();
- Run Migrations:
- Create a migration to apply the identity schema to your database.
dotnet ef migrations add CreateIdentitySchema
dotnet ef database update
Create a new file in the Data folder called DbInitializer.cs
// Data/DbInitializer.cs
using Microsoft.AspNetCore.Identity;
namespace WorldDominion.Models
{
public class DbInitializer
{
public static async Task Initialize(
UserManager<IdentityUser> userManager,
RoleManager<IdentityRole> roleManager)
{
string[] roleNames = { "Admin", "Customer" };
foreach (var roleName in roleNames)
{
var roleExist = await roleManager.RoleExistsAsync(roleName);
if (!roleExist)
await roleManager.CreateAsync(new IdentityRole(roleName));
}
// Create an Admin user
var user = new IdentityUser
{
UserName = "admin@admin.com",
Email = "admin@admin.com",
};
string userPWD = "Password@123";
var createUser = await userManager.CreateAsync(user, userPWD);
if (createUser.Succeeded)
await userManager.AddToRoleAsync(user, "Admin");
}
}
}
Add the DbInitializer as a service to our application
// Program.cs
// Registering the DbInitializer seeder
builder.Services.AddTransient<DbInitializer>();
Seed the database
// Program.cs
// Seed roles
var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
using var scope = scopeFactory.CreateScope();
var initializer = scope.ServiceProvider.GetRequiredService<DbInitializer>();
await DbInitializer.Initialize(
scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>(),
scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>()
);
dotnet add package Microsoft.AspNetCore.Authentication.Google --version 7.0.13