ASP.NET Core 6 Web API CRUD With Entity Framework

Introduction

In this article, we'll show you how to use Entity Framework to construct a WEB API in ASP.Net Core 6. ASP.NET Web API makes it easier to create HTTP(s) services that connect to various clients such as browsers and mobile devices. Building RESTful apps is best accomplished on the ASP.NET Web API platform. Use the HTTP verbs GET, POST, PUT, and DELETE  and test it using Swagger.

What is WebAPI and Why do we need it

API stands for Application Programming Interface. The HTTP Protocol is utilized by Web API, a concept that is used to increase an application's capabilities. A web-based application alone is no longer sufficient to reach all of its users or clients. People today are incredibly intelligent, which means they use technology like the iPhone, mobile phones, tablets, etc. in their daily lives. Various useful apps are available for these devices that can simplify users' lives. We can state that we are migrating from the web to the world of apps. Therefore, if we want to quickly, securely, and simply expose our service data to browsers and all of these current device apps, we need to use an API that works with both.

On the left, as you can see in the picture below, are the three applications, and on the right, as you can see in the picture below, is the database.

Our objective is to develop communication between the database and all three of these applications. A new Web API project will be added. The database will be used in this Web API Project's interactions. Also, as can be seen in the picture below, all three applications will only communicate with the database via the Web API Project.

As a result, the database is not directly accessible through these websites, Android, or iOS applications. They just need to communicate with the Web API project; the Web API project is in charge of dealing with database interactions. We require a Web API for our project because all of the business logic will be written in the Web API project alone. Web API serves as a bridge between the front-end and back-end results.

Describe HTTP Methods

Every time a client sends a request to a server, it includes an HTTP method that specifies what the client wants the server to do with the requested resource. These requested actions are represented by HTTP methods. Typical HTTP methods, for instance, can fetch data from a server, submit data to a server for processing, delete something from the server's database server, etc. The term CRUD, which stands for Create, Read, Update, and Delete, can be used to summarise a large portion of application functionality. Each of these actions has a corresponding four HTTP method which is given below

  • POST-Create
  • GET-Read
  • PUT-Update
  • DELETE-Delete

How to create Web API

Step 1 

Create a new project in Visual Studio and firstly we will install some packages from the manage Nuget package.

  • MicroMicrosoft.Entity Frameworkcore.InMemory
  • MicroMicrosoft.Entity Frameworkcore.sql server
  • MicroMicrosoft.Entity Frameworkcore.Tools

Step 2

In the solution  create a new folder and name its model inside a model to create a class and  name as Contacts inside the Contacts we have a few  properties the first property  is a Guit id and after that, we have a string of  name which will have the contacts  name after that we have an email address for the contact and that to be of type string as well and then we have a phone number which is for the contact will be of type long and lastly we have a property of address which will store the physical address of the contact and that will be of type string

public class Contact {
    public Guid id {
        get;
        set;
    }
    public string name {
        get;
        set;
    }
    public string email {
        get;
        set;
    }
    public long phone {
        get;
        set;
    }
    public string address {
        get;
        set;
    }
}

Step 3

it's now time to create a class file that will connect to our database and will act like a domain access layer because we are using an entity framework for we use the concept of the context which acts as a class that talks to the database no matter what type it is and it also features and retrieves data for us so. 

Let's create a DB contact click on a solution in a new folder call its data and insert data create a new class file name this is the contacts API which is the API name followed by the word DB contact so ContactsAPIDbContext inside the class this class will inherit from the class Db context.

Click the control that imports the dependencies using the microsoft.net Framework installed when we install the in-memory database package after that generate a constructor with which we are passing the options and the options are being passed to the base class after that in any context

We have to create properties that will act as tables for the entity framework core so creating a property only needs one property which is our contacts model. We only want to retrieve update delete and add contacts so we have a Dbset property of type contact.

public class ContactsAPIDbContext: DbContext {
    public ContactsAPIDbContext(DbContextOptions options): base(options) {}
    public DbSet < Contact > Contacts {
        get;
        set;
    }
}

Step 4

The program. cs file and inject this contacts API Db context into the services of the solution on to that injected service into a controller that we can connect to a database file and write below this line were injecting the service for swagger use the Builder.services and write at Db context because we want to add the Db context gives the type which is the contactsAPIDBcontext click control and import from contacts API data the one we created and after that, give some options to it which shows it to UseInMemoryDatabase so use InMemory database after that we have to give the database name  ContactsDb

builder.Services.AddDbContext<ContactsAPIDbContext>(option =>
option.options.UseInMemoryDatabase("ContactsDb"));

Step 5

We add a new controller in the Controller folder and select MVC Controller_empty name as Contacts now we annotate our controller with the key Api controller telling this is an API controller which shows this is not an MVC controller after that we Route our controller 

 [ApiController]
    [Route("api/[Controller]")]

Step 6

We use this private readonly field DbContext to connect to my in-memory database  and will use this dot DbContext field to connect  the contacts table

private ContactsAPIDbContext dbContext;
public ContactsController(ContactsAPIDbContext dbContext) {
    this.dbContext = dbContext;
}

Step 7

Because we've given the Db set property inside the contact, it understands that contacts are a table in a database, so connect to the contact table and return a list. Use this Db context to put a dot to connect to the contacts table. If it states that we are unable to convert type generic lists to IActionResults automatically, so we put in ok inside an ok response and its shows all the data stored in the contact table

[HttpGet]
public async Task < IActionResult > GetContacts() {
    return Ok(await dbContext.Contacts.ToListAsync());
}

Output

Step 8

In this step, we will add a contact using the AddContact method using the below C# code for HttpPost. 

[HttpPost]
public async Task < IActionResult > AddContact(AddContactRequest addContactRequest) {
    var contact = new Contact() {
        id = Guid.NewGuid(),
            name = addContactRequest.Name,
            address = addContactRequest.Address,
            email = addContactRequest.Email,
            phone = addContactRequest.Phone,
    };
    await dbContext.Contacts.AddAsync(contact);
    await dbContext.SaveChangesAsync();
    return Ok(contact);
}

Output 

Step 9 

In the GetContact method, we only retrieve single data with the key parameter Guid id.

[HttpGet]
[Route("{id:guid}")]
public async Task < IActionResult > GetContact([FromRoute] Guid id) {
    var contact = await dbContext.Contacts.FindAsync(id);
    if (contact == null) {
        return NotFound();
    }
    return Ok(contact);
}

Output

Step 10

Now we will update the contact table with key parameter guide id and UpdateContactRequest model class firstly we store the value of Guid id in the contact variable check if it is null then shows not found result if the contact is not null then update the data of the contact and show 200 response.

[HttpPut]
[Route("{id:guid}")]
public async Task < IActionResult > UpdateContact([FromRoute] Guid id, UpdateContactRequest updateContactRequest) {
    var contact = await dbContext.Contacts.FindAsync(id);
    if (contact != null) {
        contact.name = updateContactRequest.name;
        contact.phone = updateContactRequest.phone;
        contact.address = updateContactRequest.address;
        contact.email = updateContactRequest.email;
        await dbContext.SaveChangesAsync();
        return Ok(contact);
    }
    return NotFound();
}

Output

Step 11 

In this step, we will delete a contact with key parameter Guid id. Define a var type variable contact and store the parameter value check conditions  if contact is null then shows not found, if contact is not null then remove a contact from the contact table and save the changes then return 200 response 

[HttpDelete]
[Route("{id:guid}")]
public async Task < IActionResult > DeleteContact(Guid id) {
    var contact = await dbContext.Contacts.FindAsync(id);
    if (contact != null) {
        dbContext.Remove(contact);
        dbContext.SaveChanges();
        return Ok(contact);
    }
    return NotFound();
}

output

Step 12

Now implementing connection with SQL server, by adding connection string in appsettings.json 

, "ConnectionStrings": {
    "ContactAPIConnectionString": "Server=LAPTOP-L9APCEGG\\MSSSQLSERVER; Database=ContactAPIDb; User id=sa; password=Password$2; Trusted_Connection=True; MultipleActiveResultSets=true"
}

Conclusion 

In this article, we covered the topic of how we can create ASP.NET Core 6 Web API CRUD using  Entity Framework.

If you have any queries/suggestions on the article, please leave your questions and thoughts in the comment section below. Follow C# Corner to learn more new and amazing things about ASP.NET Core or to explore more technologies.

Thanks for reading and I hope you like it.