Skip to content

EF setup

chrisK00 edited this page Mar 18, 2021 · 2 revisions

Packages needed:

  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.Sqlite
  • Microsoft.EntityFrameworkCore

How to setup EF in asp.net web api

  1. First you need a class that derives from DbContext, in our case its named DataContext and placed inside /Data folder. The class should have a constructor where it receives options like this DbContextOptions<DataContext> options and passes that down to the DbContext using the base keyword. Inside this class under the constructor you can also add a dbset public DbSet<User> Users { get; set; } which represents a table in our database meanwhile the class is used to communicate with our databsase using Linq.
  2. Head to the ServiceExtensions class inside /Extensions and there is a extension method for our services to keep Startup class clean. Here you will have to register the db context to our dependancy injection container and sending down the options which currently is just the connectiong string by doing services.AddDbContext<DataContext>(options => options.UseSqlite(config.GetConnectionString("Default"))), assuming you have specified your connection string inside appsettings.json "ConnectionStrings": { "Default" : "Data Source = JokesOnYou.db" }
  3. We are all set with our code-first way of making a db but first we need to make a blueprint of how all of this will look like inside sql so we open package manager console and type add-migration Initalize now this will take you to a class with an Up and Down method. Up is what will push the changes to the real database which we do by typing update-database
Clone this wiki locally