ASP.NET Core 3: Add Entity Framework Core to Existing Project
Last week was an unofficial kicked off a series of posts associated with a refresh of the ASP.NET Basics repo frequently reference in this blog to reflect the state of affairs now that .NET Core 3 has been released. The new repo is ASP.NET Basics Refresh because naming is hard.
This post is going to take the API project created last week for the Swagger/OpenAPI with NSwag and ASP.NET Core 3 post and replace the generated data with a database using Entity Framework Core. If you want to follow along with this post the files before any changes can be found here.
Add NuGet Packages
Entity Framework Core is no longer included with .NET Core by default so we install a couple of NuGet packages to get started. I’m going to give the .NET CLI command, but this could also be done using the Visual Studio NuGet Package Manager UI. This post will also be using SQLite, but Entity Framework Core supports multiple databases you would need to install the package for the database you are interested in using.
Here are the commands to install the package we will be using. This is also assuming your terminal is in the same directory as the project file.
dotnet add package Microsoft.EntityFrameworkCore.Sqlite dotnet add package Microsoft.EntityFrameworkCore.Design
Add a DbContext
Just as a reminder we already have a Contact class in the Models directory with the following definition.
public class Contact { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string PostalCode { get; set; } public string Phone { get; set; } public string Email { get; set; } }
Next, I added a Data directory to the project and then added a new class called ContactedDbContext. The DbContext only exposes one DbSet for Contacts.
public class ContactsDbContext : DbContext { public DbSet<Contact> Contacts { get; set; } public ContactsDbContext(DbContextOptions<ContactsDbContext> options) : base(options) { } }
Configuration for the Connection String
In the appsettings.json file, which is where the application will pull configuration from by default, we are going to add a connection strings section to hold our default connection. The following is my full appsettings.json with the connection string for SQLite. If you are using a different database provider your connection string could be drastically different.
{ "ConnectionStrings": { "DefaultConnection": "DataSource=app.db" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
Check out Configuration in ASP.NET Core for more details on the different ways to handle configuration.
Register DbContext with the Services Container
Open Startup.cs and in the ConfigureServices function, we are going to use the AddDbContext extension method to add our new DbContext and tell it to use SQLite with the connection string from our appsettings.json. The following is the full function with the first two lines being the ones we added.
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ContactsDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllers(); services.AddOpenApiDocument(document => document.PostProcess = d => d.Info.Title = "Contacts API"); }
Check out the official doc for more information on Dependency injection in ASP.NET Core.
Create and Apply Initial Migration
For this bit, we are going to head back to the command line open to the directory that contains the csproj for the project we are working with. The first thing we need to do is to install the Entity Framework Core Tool using the following command which will install the tool globally.
dotnet tool install --global dotnet-ef
Next, we will create a migration called Initial that output in the Data/Migrations directory using the following command.
dotnet ef migrations add Initial -o Data/Migrations
Now that we have a migration lets use it to create our database. Note that the same command will be used in the future when applying migrations to an existing database.
dotnet ef database update
Check out the official docs for more information on the Entity Framework Core Tool or Global Tools in general.
Scaffold a New Controller
If you are using the code from GitHub at this point you will need to delete the ContactsController as it is going to be recreated using Visual Studio’s tooling.
Right-click on the directory where the controller should be created, the Controllers directory in the example, and select Add and then Controller.
On the dialog that pops up, we want to select API Controller with actions, using Entity Framework and then click Add.
On the next screen specify the model class, data context, and controller name before clicking Add. In the sample case, we are going to use our Contact class for the model, ContactDbContext for the data context to generate a controller named ContactController.
After clicking add the requested controller will be generated with all the functions needed for CRUD operations for the selected model class. The code for our sample controller can be found here.
Try it out
Running the application and hitting our swagger UI with the help of NSwag we can see all the options our API has available and even try them out which will now hit our application’s database.
Another great option to test out APIs which has a lot of really great features is Postman. Either option will allow you to try out your API without having to build a client.
Wrapping Up
Hopefully, this post will help you get a jump start on integrating Entity Framework Core in your ASP.NET Core 3 applications. As a reminder Entity Framework Core supports a lot of different database providers. If you have any question I recommend checking Microsoft’s official docs on Getting Started with Entity Framework Core.
The code with all the above changes can be found here.
ASP.NET Core 3: Add Entity Framework Core to Existing Project Read More »