In this article, we will learn how to perform the crud operations in the Asp.net core web API using the entity framework code first approach.
In this article, I will explain to you a step-by-step tutorial for performing CRUD operations in ASP.NET Core Web API using the entity framework code first approach.
we can divide the complete post into below step
- Creating Core Web API Project in VS 2019
- Install Nuget Packages in our project for Entity Framework
- Creating Model Classes & Configuring EF Core
- Setup database connection string in appsettings.json
- Creating the Database from Code Using Migrations
- Creating an API Controller
- Perform the Testing on the API End Points in Swagger
Code-First Approach
The Entity Framework introduced the Code-First approach. Some .NET developers favor working with the Designer in Code EF or database first approach while some just prefer work with their code.
At Code First, we focus on the domain of our project and start creating model classes for your domain entity instead of designing the database first. we create model classes that match our database design. It means to say that in the code first approach we create the database from model classes i.e Code First modeling approach create a database that doesn’t exist in our database and Code First will create it first.
If you want to use the database first approach read below article
Create ASP.NET Core Web API Project
- Open Visual Studio ,Click to >Create a new Project>Asp .Net Core Web Application
Install Nuget Packages in our Web Api Core project
Now we have running build project and You can check this by using F5 to run the API. It will open the swagger page for testing the API.
Now we need to install some Entity Framework core packages from the NuGet package manager to perform database Crud operations from C# code.
First Package- Microsoft.EntityFrameworkCore.SqlServer
This NuGet package provides classes for Entity Framework Core to connect to SQL Server for database operations.
Second Package- Microsoft.EntityFrameworkCore.Tools
This Nuget package will support us to work with database-related activity like adding migration for database, script migration, DB context, update Object database, etc.
So we have created a Core API application and installed the required Entity Framework Core Nuget packages that need for Code First Migration, to use Entity Framework Core features to work with SQL Server Database
Creating Model Classes & Configuring EF Core
So, let’s move and create a folder name as ‘Model’ and create a Model class as ‘TblCustomer‘ in with the following properties.
The class above defines the class TblCustomer with some properties. Additionally, we have decorated the CustomerId property with Key and DatabaseGenerated attributes because we will be turning this class into a database table and the column CustomerId will serve as the primary key Column with the auto-incremented identity that means you can say that we declaring CustomerId as primary-key with Identity.
public class TblCustomer { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long CustomerId { get; set; } public string CustomerName { get; set; } public string CustomerNumber { get; set; } public string CustomerEmail { get; set; } }
As the next step, We will create another class inside the Model folder as ‘CustomerDbContext’ that will inherit to DbContext class and define the database connection and register the context in our application.
This class will contain all the information which is responsible for creating and updating the tables in our database.
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CrudCodeFirst.Model { public class CustomerDbContext : DbContext { public CustomerDbContext(DbContextOptions options) : base(options) { } public DbSet<TblCustomer> TblCustomer { get; set; } } }
As we know that in the EF Code First approach, first We need to write the Model classes, and on the basis of these Model classes our database tables are generated in the database.
Setup database connection string in appsettings.json
To create these tables in the database let’s define the database connection in the appsettings.json file.
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "myconn": "server=SQLEXPRESS01;initial catalog=CustomerDb;user id=***;password=****;multipleactiveresultsets=True;" }, "AllowedHosts": "*" }
To use the database connection string, register our context in the Startup.cs class as follows.
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "CrudCodeFirst", Version = "v1" }); }); services.AddDbContext<CustomerDbContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn"))); }
So, the next step is to generate the database using Entity Framework Core Migrations.
Open Package Manager Console from the Tools Menu and run the following command in the Package Manager console: ‘add-migration MigrationName’
let’s run this command and see what happens. In the Nuget Package Manager Console, just type the ‘add-migration DataBaseSetup” command and press Enter.
This migration command creates a folder name as ‘Migrations’ in our web API project and creates the class with the name [MigrationName] as which we provided while running add migration command.
Here you can see the table structure based on your Model TblCustomer,
using Microsoft.EntityFrameworkCore.Migrations; namespace CrudCodeFirst.Migrations { public partial class DataBaseSetup : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "TblCustomer", columns: table => new { CustomerId = table.Column<long>(type: "bigint", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), CustomerName = table.Column<string>(type: "nvarchar(max)", nullable: true), CustomerNumber = table.Column<string>(type: "nvarchar(max)", nullable: true), CustomerEmail = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_TblCustomer", x => x.CustomerId); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "TblCustomer"); } } }
Now We have created the migration script for creating the database and table. and we know that we didn’t create the database and tables in the SQL server.
So, let’s run the migration script to create the database and tables. execute command ‘update-database‘ in the package manager console.
When the command executes successfully, open your SQL Server Management Studio, you can able see the database, table, and Entity Framework Migration history table as follows.
Create a API Controller
Now Let’s Create a API Controller for Performaing crud operations in our table, So, Let’s add a new API controller name as TblCustomersController.
- Right-click on controller folder in the Project
- Add>controller> choose Api Controller from left side
- Select Empty controller
Or create a controller using entity framework using template
you can also choose read/write action using entity framework, it will create all necessary endpoints for you. using a read/write template you don’t need to write the code manually. it will auto generate the code.
My suggestion is that for learning purposes you should create an empty controller and write code yourself instead of autogenerated code.
- Right-click on controller folder in the Project
- Add>controller> choose Api Controller from left side
- Select Api controller with actions using entity framework
- Choose Model Class
- Select DbContext
- Give Controller and then click on Add Button
TblCustomersController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using CrudCodeFirst.Model; namespace CrudCodeFirst.Controllers { [Route("api/[controller]")] [ApiController] public class TblCustomersController : ControllerBase { private readonly CustomerDbContext _context; public TblCustomersController(CustomerDbContext context) { _context = context; } // GET: api/TblCustomers [HttpGet] public async Task<ActionResult<IEnumerable<TblCustomer>>> GetTblCustomer() { return await _context.TblCustomer.ToListAsync(); } // GET: api/TblCustomers/5 [HttpGet("{id}")] public async Task<ActionResult<TblCustomer>> GetTblCustomer(long id) { var tblCustomer = await _context.TblCustomer.FindAsync(id); if (tblCustomer == null) { return NotFound(); } return tblCustomer; } // PUT: api/TblCustomers/5 // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPut("{id}")] public async Task<IActionResult> PutTblCustomer(long id, TblCustomer tblCustomer) { if (id != tblCustomer.CustomerId) { return BadRequest(); } _context.Entry(tblCustomer).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TblCustomerExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/TblCustomers [HttpPost] public async Task<ActionResult<TblCustomer>> PostTblCustomer(TblCustomer tblCustomer) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _context.TblCustomer.Add(tblCustomer); await _context.SaveChangesAsync(); return CreatedAtAction("GetTblCustomer", new { id = tblCustomer.CustomerId }, tblCustomer); } // DELETE: api/TblCustomers/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteTblCustomer(long id) { var tblCustomer = await _context.TblCustomer.FindAsync(id); if (tblCustomer == null) { return NotFound(); } _context.TblCustomer.Remove(tblCustomer); await _context.SaveChangesAsync(); return NoContent(); } private bool TblCustomerExists(long id) { return _context.TblCustomer.Any(e => e.CustomerId == id); } } }
Perform Testing with Help of Swagger or you can use postman also
Now build project and take a look at the browser. You can see swagger page. now let’s call our Api.
1. Create Customer Object in database
POST–api/TblCustomers
The PostTblCustomer action method will handle HTTP POST requests and make an entry in the database table.
// POST: api/TblCustomers [HttpPost] public async Task<ActionResult<TblCustomer>> PostTblCustomer(TblCustomer tblCustomer) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _context.TblCustomer.Add(tblCustomer); await _context.SaveChangesAsync(); return CreatedAtAction("GetTblCustomer", new { id = tblCustomer.CustomerId }, tblCustomer); }
The PostTblCustomer action method will handle HTTP POST requests and make an entry in the database table.
In the PostTblCustomer method, we first validating the model using ModelState.IsValid. This will make sure that the TblCustomer object includes all the required information. If this is not true then you get a BadRequest response. If TblCustomer model i.e data is model then add TblCustomer using Entity Framework context and return CreatedAtAction status response.
Request body
{ "customerName": "Mark", "customerNumber": "12346679", "customerEmail": "test@gmail.com" }
Response body
{ "customerId": 1, "customerName": "Mark", "customerNumber": "12346679", "customerEmail": "test@gmail.com" }
- Let’s do test on swagger, Click Post tab,then click on Try it Out Button
- Input Body parameter and click on the excute button
2. Get All Customers
GET: api/GetTblCustomer
The following GetTblCustomer() action method in TblCustomer class returns all the Customer from the database using Entity Framework.
// GET: api/TblCustomers [HttpGet] public async Task<ActionResult<IEnumerable<TblCustomer>>> GetTblCustomer() { return await _context.TblCustomer.ToListAsync(); }
- Let’s do test on swagger, Click Get /api/TblCustomers tab,then click on Try it Out Button
- Click on the excute button
It will return all customer records in the Tblcustomer table, right now we only have one record that’s why it returns only one object.
Response body
[ { "customerId": 1, "customerName": "Mark", "customerNumber": "12346679", "customerEmail": "test@gmail.com" } ]
3. Get Customer by Id
GET: api/TblCustomers/1
It will return all Customer with id=1 in the database
As you can see in the below code, GetTblCustomer() method returns Customer by Id using EF. If no Customer exists in the database table then it will return 404 NotFound responses otherwise it will return 200 OK responses with Customer data.
The NotFound() and Ok() methods defined in the Tblcustomer returns 404 and 200 response respectively according to our condition.
// GET: api/TblCustomers/5 [HttpGet("{id}")] public async Task<ActionResult<TblCustomer>> GetTblCustomer(long id) { var tblCustomer = await _context.TblCustomer.FindAsync(id); if (tblCustomer == null) { return NotFound(); } return tblCustomer; }
- Let’s do test on swagger, Click Get /api/TblCustomers/{id} tab,then click on Try it Out Button
- Enter Customer Id for find record,Click on the excute button
Return the database record with Id=1
Response body
{ "customerId": 1, "customerName": "Mark", "customerNumber": "12346679", "customerEmail": "test@gmail.com" }
4. PUT–/api/TblCustomers/1
This Put is used to update the TblCustomer table in the database, You just need to pass the TblCustomer object in the request body, and in response, you will able to get an updated TblCustomer record.
PutTblCustomer() action method in our TblCustomerController is used to update an existing Customer record in the database using Entity Framework.
[HttpPut("{id}")] public async Task<IActionResult> PutTblCustomer(long id, TblCustomer tblCustomer) { if (id != tblCustomer.CustomerId) { return BadRequest(); } _context.Entry(tblCustomer).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TblCustomerExists(id)) { return NotFound(); } else { throw; } } return NoContent(); }
- Let’s do test on swagger, Click PUT /api/TblCustomers/{id} tab,then click on Try it Out Button
- Enter Customer Id for which you want to update the record,and let’s update record with Id=1
- Input updated value,Click on the excute button,
- It will update customer record with Id=1
Request body
{ "customerId": 1, "customerName": "Mark New Name", "customerNumber": "9989898989", "customerEmail": "mark@gmail.com" }
5. DELETE Doctor by Id
DELETE:/api/TblCustomers/1
It will delete the Customer with id=1 in the database
DeleteTblCustomer() action method in our TblCustomerController use to delete an existing Customer record in the database using Entity Framework.
// DELETE: api/TblCustomers/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteTblCustomer(long id) { var tblCustomer = await _context.TblCustomer.FindAsync(id); if (tblCustomer == null) { return NotFound(); } _context.TblCustomer.Remove(tblCustomer); await _context.SaveChangesAsync(); return NoContent(); }
- Let’s do test on swagger, Click DELETE /api/TblCustomers/{id} tab,then click on Try it Out Button
- Enter Customer Id for deleting record,Click on the excute button
So, in this post, we have seen how to perform creating ASP.NET Core Web API using Entity Framework Core Code First approach, if you have any queries or doubts, please comment.
The post .NET Core Web API Using Code First Entity Framework Approach appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- How to enrich azure b2c token with custom claims using api connectors and asp net core web api
- Image Uploading in Dot net core Web API
- Web api 2 and Mongodb v2 Migrate sample code to using driver version 2
- How to Publish a Web API net core 3.0 in multiple servers
- Upload Large Files using Angular 8 and .Net Core Web API
- CamelCase not working in net core 6 web api
- JWT Authentication using a custom attribute in .NET Core Web API
- Hardcoded paths in autogenerated web.config when using IIS with .NET Core 2.2 Web API
- How to mock ExceptionContext for testing using .NET Core 3 Web API and Moq
- .NET Core Web API and MongoDB Driver using Generic JSON Objects
- How do I connect to database in ASP.NET Core Web API without using EF?
- Using ZipArchive with ASP.NET Core Web Api
- 'Page not found' error on my controller for my NET Core Web API
- Can't bind params using [FromQuery] ASP Net Core 2 API
- No 'Access-Control-Allow-Origin' header is present - asp.net core web api targeting .net framework 4.5.1
- Download file from dotnet Core Web API using POST in ASP.NET MVC 5 controller
- authenticate MVC website user from Web API by using MVC Core Identity
- What is the equivalent code for the asp.net core DI framework from this example using Ninject?
- Using Microsoft Graph token to secure ASP.NET Core Web API with Jwt Bearer tokens
- .net Core 2.0 web api 400 error using Validateantiforgerytoken
- How do I display Dropbox image files in an ASP.NET web page using Core API in C#
- Asp Net Core Web Api POST Request.Body always length 0
- Web Api Scaffolding - Error running the selected code generator
- Am I using DataContractJsonSerializer or the Json.net one in my web api 2
- How should I store per request data when using OWIN to Self-Host ASP.NET Web API
- Asp.net Core rc2 web api file upload
- Web Api Content.ReadAsAsync method not found, but code compiles
- Cant get the asp.net Web API token using http client
- Dictionary<string, object> serialization in OData using ASP.Net MVC 5 and Web API 2.0
- ASP.Net Core routes with Web API
- How to forward a REST web service using C# (WCF)?
- IronPython - Load script from string in C# 4.0 application
- BitArray Thread Safety
- WPF models appear black with helix viewer 3d c#
- Ninject 2: Is there an equivalent to 1.5's InjectPropertiesWhere?
- 1E-08 to decimal
- Unable to upload file with emulator, problem with controller
- RegistryTreeChangeEvent via C# & WMI
- Blazor WebAsembly Access Database
- HttpClient POST generates GET instead
- asp.net azure active directory user profile data
- Long Process in ASP.NET Web Forms - Browser Timeout
- How do you find an element index in a Collection<T> inherited class?
- Run other project when running unit tests in Visual Studio 2013
- Math function to remove minus
- Auto Hot Keys with coding text
- Access View State in ashx file
- How can I use open hardware monitor source code in c# ? I tried anything doesn't work
- What is the verifier in DotNetOpenAuth's DesktopConsumer ProcessUserAuthorization?
- CSOMUnknownUser error on working with draft project in Project Server 2013 CSOM