Saturday, August 10, 2019

Adding Entity Framework Core to the WebAPI Project

In the previous post we saw on how to create a basic WebAPI project in Asp.Net Core using Visua Studio 2017. In this post we shall see on how to add Entitiy Framework Core support to the basic project. First let us create a class Library project with name DataAccess. This project will deal with all database interactions and we will implement EntityFramework Core in this project.

Once the DataAccess project is created, delete the default class1.cs which got created with the project. Add the following NuGet packages using the NuGet package Manager.




Open the DataAccess project file and add the following line to the Project file

The Project file will be as follows.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
  </ItemGroup>
   <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />
  </ItemGroup>
   <ItemGroup>
     <Folder Include="Model\" />
   </ItemGroup>
</Project>
Next Add a folder Model in the Project, the model classes will be created inside this folder. Next open visual studio command prompt and run the following command to generate the model classes from the database.

HelloWebAPI\DataAccess>dotnet ef dbcontext Scaffold "Server=<ServerName>\SQLEXPRESS;Database=UserRegistration;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Model 

Once this command gets executed, a context file UserRegistrationContext.cs and one Model class per table in the database will be created in the Model folder.




Notice that the connection string is hard-coded in the context class, we can move this to a config file and reference it from the config file, so that it will be easy to deploy the project in different environments.

If we add new database objects or change structure at a later stage, we will have to re-generate the Model classes using the force –f option as follows.

HelloWebAPI\DataAccess>dotnet ef dbcontext Scaffold "Server=<ServerName>\SQLEXPRESS;Database=UserRegistration;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Model -f



Search Flipkart Products:
Flipkart.com

No comments: