Hello All, Welcome back to Knowledge Base.
Today we will learn how to work with Entity framework in .NET Core Application.
Lets get started by creating the application. As the same process we need to create a new project and choose web application and select ASP.NET Web Application (.NET Core).
If you don't have .NET Core installed in your visual studio. Download it from here .NET Core
Once the project creation is done. Now we need to create models in our project. For this sample we will be creating a Person model.
After creating model, we will start dealing with creating a DbContext.
What is a DbContext?
The primary class that is responsible for interacting with data as objects is System.Data.Entity.DbContext (often referred to as context). The context class manages the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database.
Now we need to configure the application to work with EntityFramework and use SqlServer as our database. And also we need to Add out DbContext to that. Prior to that we need to specify a connection string which maps to a database server.
Open appsettings.json, add the below connection string. You can change the connection string according to your project.
In the above snippet we are grouping the connection strings in one key, "Data". When ever we need to access connection string we will be using this key to access the connection string. For example if I want to retrieve the SampleConnection connection string then I need to write Data:SampleConnection
Now we will configure our services. Open the Startup.cs file and in the ConfigureServices method add the below code.
We need to inclue some packages to our project which helps in running dotnet commands. We need to write them in project.json.
Once you save the file you can observe in the solution explorer that the packages are restoring in to our solution.
Now we will add some logic in our controller to access the entity data.
Once all the process is done. Now we need to create migrations for our project to create database. Go to Command Prompt and navigate to the project and there we will execute dotnet commands. Or Right click on the project and Choose Command Line as shown below.
To Create migrations run the below commands.
> dotnet ef migrations add InitialDBCreate
We can able to see the migrations created in our project. Now we need to update the database using this migration. Run the below commands which updates the database.
> dotnet ef database update
Now run the application and put a break point at home controller where we have written code for fetching person data. You see we get data count as 0. You can have some seed data that can be populated when we run the application for the first time.
Hope this sample helps in starting working with Entity framework in .NET Core application.
Following is the sample code.