Saturday 15 May 2021

Part 8 : EF Core in Web API

#5 Minutes Of Reading

In this article I will show you how to implement entity framework and how useful dependancy injetcion, I’m moving to database data from in memory data without affecting controller code. This is the advantage of using DI in application. You will came to know as later in this course. Source code available here Change model name from User to Employee shown below.
Add class EmployeeDbContext which is resposible add/modify SQL database. Property with type DbSet represent database table as property in c#.
Open appSettings.Json file and add connection string here.
Open Startup.cs file and add below highlighted line of code to configure EF core in ConfigureService method.
Everything is set up to create database with employee table. From visual studio go to tools -> NugetPackageManager -> PackageManagerConsole
Enter Add-Migration command under package manager console window shown highlighted.
I have commented code for repository ‘EmployeeRepository’ is resposible to read data from in-memory data and EmpRepository is responible for reading data from EF core.
The benefit of using dependancy injection, high level object not change, here in this Employee controller code is same for EmployeeRepository (in-memory) and EmplRepository(Ef Core). Changes done in backend and controller referencing interface which is common for both repository.
Run application and add record for employee in database table using POST method.
Create EmpRepository shown below which inherit same interface which I used for in-memory data.
Update Startup.cs to refer updated repository.
Now this is the power of dependancy injection, commented code with EmployeeRepository is resposible to read data from in-memory data and EmpRepository is responible for reading data from EF core.
The benefit of using dependancy injection, high level object not change, here in this Employee controller code is same for EmployeeRepository (in-memory) and EmplRepository(Ef Core). Changes done in backend and controller referencing interface which is common for both repository.
Run application and add record for employee in database table using POST method.
Click on POST button, again click on TryOut button, modify data shown below highlighted and click on execute button.
Data added in database table.
Add few more records for employee and test all remaining Http post methods implemented in Employee controller.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home