Skip to content

Latest commit

 

History

History
67 lines (58 loc) · 1.99 KB

steps.md

File metadata and controls

67 lines (58 loc) · 1.99 KB

Terminal commands

// only need to do this once on our computer.
dotnet tool install --global dotnet-ef

//Adding packages
dotnet add package Pomelo.EntityFrameworkCore.MySql --version 3.1.1
dotnet add package Microsoft.EntityFrameworkCore.Design --version 3.1.5

After create the classes we need to create the migration.

// Create the migration - Change the YourMigrationName to the name of the migration
dotnet ef migrations add YourMigrationName

// Apply the migration
dotnet ef database update

Files to Modify

  • modify appsettings.json -- change the databasename

  • modify startup.cs -- change the connection string


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext(options => options.UseMySql(Configuration["DBInfo:ConnectionString"]));
            
            services.AddControllersWithViews();
        }
  • create MyContext.cs file -- Example bellow

using Microsoft.EntityFrameworkCore;

namespace CRUDelicious.Models
{ 
    // the MyContext class representing a session with our MySQL 
    // database allowing us to query for or save data
    public class MyContext : DbContext 
    { 
        public MyContext(DbContextOptions options) : base(options) { }
        // the "Monsters" table name will come from the DbSet variable name
        public DbSet Dishes { get; set; }
    }
}
  • modify HomeController.cs -- Example bellow

 public class HomeController : Controller
    {
        private readonly ILogger _logger;
        private MyContext dbContext;
    
        // here we can "inject" our context service into the constructor
        public HomeController(MyContext context,ILogger logger)
        {
            _logger = logger;
            dbContext = context;
        }
        // the Index method will query the database bellow