Since .NET Core 2.0 was released, Microsoft has published its source code for .NET Core. As a result, you can now use the same .NET Core source code that powers Windows Store apps with other server-side applications. This is awesome news because it means you can use the same ASP.NET Core source code you’ve been using with your web applications and it will work hand-in-hand with any .NET Framework compatible applications you’ve developed in the past.
.NET Core is Microsoft’s latest and greatest continuation of their .NET framework. While the full framework is available for windows, it only supports x86 processors and is not cross-platform. The .NET Core SDK is available for Linux, Mac and Windows (even 32 bit) and is a separate framework from the Core CLR. The Core framework allows you to write applications that run on all the .NET platforms and will be future-proofed for years to come by not having to support an aging Windows platform.
I took a break from programming for a month to go on vacation to the Philippines for Christmas. It was the best decision I made in my life because it made me realize how important time was. I used to program everyday, either 10-11 hours or even longer. On the internet, you can find everything and anything. People only think about what they want to know, not about how much they learn. I have compiled my notes about this vacation so that others may benefit from it.
In this article, we will learn how to perform coarse operations in the Asp.net Core Web API by using the entity code approach.In this article, I will give you a step-by-step guide on how to perform CRUD operations in ASP.NET Core Web API using the entity-based code approach.
Contents
- we can divide the entire contribution into the following steps
- Approach code
- Creating an ASP.NET Core Web API project
- Installing the Nuget packages in our Web Api Core project
- Creating Template Classes and Configuring EF Core
- Setting the database connection string in appsettings.json
- Creating a PLC controller
- Perform the test with Swagger or you can also use postman
- 1. Creating a customer object in the database
- 2. Reception of all customers
- 3. Receive customer ID
- 5. DELETE doctor after Id
- Frequently Asked Questions
we can divide the entire contribution into the following steps
- Creating a Core Web API project in VS 2019
- Install the Nuget packages for Entity Framework in our project
- Creating Model Classes and Configuring EF Core
- Define the database connection string in the appsettings.json file
- Create a database from code with migrations
- Create an API controller
- API endpoint testing in Swagger
Approach code
Entity Framework introduced the code-first approach. Some .NET developers prefer to work with the constructor in the EF code or with the database, and others prefer to work with their code alone.
At Code First, we focus on the project domain and start by creating model classes for your domain entity rather than designing the database first. We create model classes that match our database design. This means that in the code-first approach we create a database from the classes in the model, i.e. the code-first model approach creates a database that does not exist in our database, and creates it code-first.
Creating an ASP.NET Core Web API project
- Open Visual Studio, click on >Create New Project>Asp .Net Core Web Application
Installing the Nuget packages in our Web Api Core project
We have an ongoing build project right now, and you can verify it by using F5 to run the API. This will open the Swagger page for API testing.
Now we need to install some entity framework kernel packages from the NuGet package manager to perform raw database operations from the C# code.
The first package is Microsoft.EntityFrameworkCore.SqlServer.
This NuGet package contains classes that enable Entity Framework Core to connect to SQL Server for database operations.
The second package is Microsoft.EntityFrameworkCore.Tools.
This Nuget package helps us to manage database related activities like adding migrations for databases, migrating scripts, database context, updating object database, etc.
So we created a Core API application and installed the necessary Nuget Entity Framework Core packages for Code First Migration to use the Entity Framework Core features to work with a SQL Server database.
Creating Template Classes and Configuring EF Core
So let’s create a folder named Model and create a model class named TblCustomer with the following properties.
The above class defines the TblCustomer class with some properties. We have also provided the CustomerId property with the attributes Key and DatabaseGenerated because we are going to convert this class into a database table and the column CustomerId will serve as a column primary key with an auto-incremented identity, i.e. we can say that we declare CustomerId as a 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; }
}
The next step is to create another class in the Model folder, called CustomerDbContext, which inherits from the DbContext class, defines the database connection, and registers the context in our application.
This class will contain all the information 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 { get ; set ; }
}
}
As we know, in the EF code-first approach, we have to write model classes first, and based on these model classes, our tables are created in the database.
Setting the database connection string in appsettings.json
To create these tables in the database, we need to define the database connection in the appsettings.json file.
{
Logging : {
LogLevel : {
Standard : 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(item => item.UseSqlServer(Configuration.GetConnectionString(myconn));
}
The next step is to create the database using Entity Framework Core Migrations.
Open the 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, type the command add-migration DataBaseSetup and press Enter.
This migration command creates a folder called Migrations in our Web API project and creates a class called [Migration Name], which we specified when we ran the Add Migration command.
Here you see the structure of the table based on your TblCustomer template,
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(type : bigint, nullable : false)
.Annotation(SqlServer:Identity, 1, 1),
CustomerName = table.Column(type : nvarchar(max), nullable : true),
CustomerNumber = table.Column(type : nvarchar(max), nullable : true),
CustomerEmail = table.Column(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 a migration script to create the database and tables. and we know that we have not created the database and tables on SQL Server.
So run the migration script to create the database and tables. Run the update database command in the package manager console.
After you run the command successfully, open SQL Server Management Studio and you can see the Entity Framework Migration database, table, and history table as follows.
Creating a PLC controller
Now let’s create an API controller to perform some raw operations on our table, so let’s add a new API controller called TblCustomersController.
- Right-click on the controller folder in the project.
- Add>Controller>Select Api controller on the left side
- Select an empty controller
Or create a controller using an entity skeleton using the
You can also choose a read/write action with the entity frame, it will create all the necessary endpoints for you. If you use the read/write model, you don’t have to write code manually, the code is generated automatically.
I suggest, for training purposes, that you create an empty controller and write the code yourself instead of using the automatically generated code.
- Right-click on the controller folder in the project.
- Add>Controller>Select Api controller on the left side
- Selection of Api controllers with actions via Entity Framework
- Select the model class
- Select DbContext
- Specify the controller and then click the 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>> GetTblCustomer()
{
return await _context.TblCustomer.ToListAsync();
}
// GET: api/TblCustomers/5
[HttpGet({id})]
public async Task<ActionResult> GetTblCustomer(long id)
{
var tblCustomer = await _context.TblCustomer.FindAsync(id);
if (tblCustomer == null)
{
return NotFound();
}
return tblCustomer;
}
// PUT : api/TblCustomers/5
// To protect against over-post attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut({id})]
public async Task PutTblCustomer(long id, TblCustomer tblCustomer)
{
if (id != tblCustomer.CustomerId)
{
return BadRequest();
}
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> 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 DeleteTblCustomer(long id)
{
var tblCustomer = await _context.TblCustomer.FindAsync(id);
if (tblCustomer == null)
{
return NotFound();
}
_context.TblCustomer.Remove(tblCustomer);
wait for _context.SaveChangesAsync() ;
return NoContent();
}
private bool TblCustomerExists(long id)
{
return _context.TblCustomer.Any(e => e.CustomerId == id);
}
}
}
Perform the test with Swagger or you can also use postman
Now put the project together and look at the browser. You can see the Swagger page. Now we want to give our api a name.
1. Creating a customer object in the database
POST-api/TblCustomers
The PostTblCustomer action method processes HTTP POST requests and enters a record in the database table.
// POST : api/TblCustomers
[HttpPost]
public async Task<ActionResult> 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 processes HTTP POST requests and creates a record in the database table.
In the PostTblCustomer method, we first check the model with ModelState.IsValid. This ensures that the TblCustomer object contains all the necessary information. Otherwise you will get a BadRequest response. If the model is TblCustomer, i.e., the data is a model, add a TblCustomer using the Entity Framework context and return the CreatedAtAction state response.
Housing Application
{Client name: Mark,
customer number: 12346679,
email customer: [email protected]
}
Answering body
{
customerId: 1,
customerName: Mark,
customer number: 12346679,
email customer: [email protected]
}
- Let’s go to swagger, click on the Post tab, then click on Try it out.
- Enter the Body parameter and press the output key.
2. Reception of all customers
GET : api/GetTblKlant
The GetTblCustomer() next action method of the TblCustomer class returns all the customers in the database using the Entity Framework.
// GET: api/TblCustomers
[HttpGet]
public async Task<ActionResult<IEnumerable>> GetTblCustomer()
{
return await _context.TblCustomer.ToListAsync();
}
- Let’s do a Swagger test, click on the Get /api/TblCustomers tab, then click on Try it Out.
- Press the eject button
It returns all the customer records in the table Tblcustomer. Right now we only have one record and it only returns one object.
Please contact
[
{
customerId : 1,
customerName : Mark,
customer number: 12346679,
customer email: [email protected]
}
]
3. Receive customer ID
GET: api/TblCustomers/1
This returns all customers with id=1 in the database.
As you can see in the following code, the method GetTblCustomer() returns the customer based on the id with EF. If there are no clients in the database table, a 404 NotFound response is returned, otherwise a 200 OK response with client data is returned.
The methods NotFound() and Ok() defined in Tblcustomer return the response 404 and 200, respectively, based on our condition.
// GET : api/TblCustomers/5
[HttpGet({id})]
public async Task<ActionResult> GetTblCustomer(long id)
{
var tblCustomer = await _context.TblCustomer.FindAsync(id);if (tblCustomer == null)
{
return NotFound();
}
return tblCustomer;
}
- Let’s do a Swagger test, click on the Get /api/TblCustomers/{id} tab, then click on Try it Out.
- Enter the ID of the physician for whom you are seeking an appointment and click the View button.
Enter the database record with Id=1
Please contact
{
customerId: 1,
customerName: Mark,
customer number: 12346679,
email customer: [email protected]
}
4. PUT-/api/TblCustomer/1
This operation updates the TblCustomer table in the database. Just provide a TblCustomer object in the request body, and you can get an updated TblCustomer record as a response.
The PutTblCustomer() action method of our TblCustomerController is used to update an existing customer record in the database using the Entity Framework.
HttpPut({id})]
public async Task 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 a test swagger, click on the PUT/api/TblCustomers/{id} tab, then click on Try it Out.
- Enter the Id of the physician for whom you want to update the record and have us update the record with Id=1.
- Enter the updated value, press the excute key,
- This will update the client record with Id=1.
Housing Application
{
customerId: 1,
customerName: Mark new name,
customer number : 99898989,
customerEmail : [email protected]
}
5. DELETE doctor after Id
DELETE:/api/TblCustomers/1
This operation removes the customer with ID=1 from the database.
The DeleteTblCustomer() action method of our TblCustomerController is used to delete an existing customer record in the database using the Entity Framework.
// DELETE : api/TblCustomers/5
[HttpDelete({id})]
public async Task 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 a test swagger, click on the DELETE /api/TblCustomers/{id} tab, then click on Try it Out.
- Enter the ID of the physician to delete the record and click the Delete button.
So in this post we have how to create ASP.NET Core Web API using Entity Framework Core Code First approach, if you have any questions or doubts please comment.As we know, .NET Framework and ASP.NET MVC support project-scoped application settings and configurations. This means your application must have a Code First database. In ASP.NET Core MVC, we use Code First as the database engine. Code First works with Entity Framework 6.1, which requires an EF6 database, or later.. Read more about asp.net core entity framework database first and let us know what you think.
Frequently Asked Questions
How do I use code first in Entity Framework Core?
Code First is a feature of Entity Framework that enables data to be written to your database in the most efficient way, eliminating the need for manual data migrations and the potential of human error. In this blog post, we will go over the basics of how to use Code First in your applications, and take a look at how to use it both in Entity Framework Core and Entity Framework 6. Code first is a process to create a database first, and then the logic to populate the database from code. Code first is a step up from generating a database first, and then populating it with code. This process is more efficient and more flexible.
Can you use Entity Framework with .NET core?
We’ve all been there, at some point, either having to write code for a web application that has to handle a database, or trying to work with a legacy system that is still using .NET 4.0. There is a common misconception in the .NET community that Entity Framework is not supported in .NET Core. This is not entirely accurate, though it is not supported as a whole either. Entity Framework is supported as a Code First database provider, since core does not offer any other database provider support. This blog will show you how easy it is to use .NET Core and Entity Framework together to build an API.
What is code first in Entity Framework Core?
Entity Framework Core is a new framework from Microsoft that is powered by Code First. It provides an easy and flexible way to create a database-first application in a consistent way, using an MVC-like framework. If you are interested in learning more about Entity Framework Core, then check out my post which describes the basics of Entity Framework Core. In this post, I am going to introduce you to a code-first approach to designing an ASP.NET Core application with Entity Framework Core, which is a part of Microsoft.
Related Tags:
asp.net core entity framework database firstcreating web api using code-first approach in entity frameworkentity framework core tutorial.net core entity frameworkasp.net core web api with ef core code-first approachasp.net core web api with ef core database-first approach,People also search for,Feedback,Privacy settings,How Search works,asp.net core web api with ef core code-first approach,asp.net core web api with ef core database-first approach,entity framework core code first migrations,.net core 3.1 entity framework code first,asp.net core entity framework database first,creating web api using code-first approach in entity framework,entity framework core tutorial,.net core entity framework