###### tags: `Template` # CSharp File Templates ## Add Packages: ``` dotnet add package Pomelo.EntityFrameworkCore.MySql --version 6.0.1 dotnet add package Microsoft.EntityFrameworkCore.Design --version 6.0.3 ``` ## appsettings.json file - Edit the user/pass and db name as needed ``` { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "DefaultConnection": "Server=localhost;port=3306;userid=root;password=root;database=monsterdb;" } } ``` ## Program.cs ``` using Microsoft.EntityFrameworkCore; using <ProjectName>.Models; var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddControllersWithViews(); builder.Services.AddHttpContextAccessor(); builder.Services.AddSession(); builder.Services.AddDbContext<MyContext>(options => { options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)); }); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseSession(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); ``` ## Model Files ``` #pragma warning disable CS8618 using System.ComponentModel.DataAnnotations; namespace <ProjectName>.Models; public class <className> { } ``` ### Models/MyContext.cs - Create this file in the Model folder ``` #pragma warning disable CS8618 // We can disable our warnings safely because we know the framework will assign non-null values // when it constructs this class for us. using Microsoft.EntityFrameworkCore; namespace <YourProjectName>.Models; // the MyContext class represents a session with our MySQL database, allowing us to query for or save data // DbContext is a class that comes from EntityFramework, we want to inherit its features public class MyContext : DbContext { // This line will always be here. It is what constructs our context upon initialization public MyContext(DbContextOptions options) : base(options) { } // We need to create a new DbSet<Model> for every model in our project that is making a table // The name of our table in our database will be based on the name we provide here // This is where we provide a plural version of our model to fit table naming standards public DbSet<Monster> Monsters { get; set; } } ``` ### Add this line to all class Model files (tables) ``` public DateTime CreatedAt { get; set; } = DateTime.Now; ``` ## Controler Files ``` using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using <ProjectName>.Models; namespace <ProjectName>.Controllers; public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private MyContext _context; public HomeController(ILogger<HomeController> logger, MyContext context) { _logger = logger; _context = context; } public IActionResult Index() { // List<ClassName> All<ClassName> = _context.<VarOnContextFile>.ToList(); return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } ``` # Commands ``` dotnet new mvc --no-https -o ProjectName ``` ``` dotnet ef migrations add FirstMigration ``` ``` dotnet ef database update ```