-
Notifications
You must be signed in to change notification settings - Fork 11
EF setup
chrisK00 edited this page Mar 18, 2021
·
2 revisions
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.Sqlite
- Microsoft.EntityFrameworkCore
How to setup EF in asp.net web api
- 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 thebase
keyword. Inside this class under the constructor you can also add a dbsetpublic DbSet<User> Users { get; set; }
which represents a table in our database meanwhile the class is used to communicate with our databsase using Linq. - 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" }
- 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 typingupdate-database