×
iFour Logo

ASP.NET CORE API with Entity Framework

iFour Team - November 20, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

Sustainable

Introduction

The ASP.NET Core is a free open-source and cross-platform framework for creating cloud-based applications, such as web applications, IoT applications and mobile backends. ASP.NET Core MVC is a middleware that provides a framework for creating APIs and web applications using MVC.

HTTP is not just for serving web pages. It is also a powerful platform for creating APIs that reveal services and data. HTTP is simple, flexible and ubiquitous. Most of the platform you can think of has an HTTP library, so HTTP services can reach a wide range of customers, including browsers, mobile devices and traditional desktop applications.

ASP .NET Core has built-in support for MVC Building Web API. Integrating the two frameworks makes it easier to create applications that include both UI (HTML) and API, as they now share the same code base and pipeline.

Overview

Here is the API you created:

The following figure shows the basic design of the application.

HTTP

The client is whatever consumes the web API (browser, mobile application and so on). We are not writing clients in this tutorial.

The model is an object that represents data in your application. In this case, the only model has to do item. Model are represented as Simple C # Class (POCO).

A controller is an object that handles HTTP requests and generates HTTP responses. This application will have a single controller.

Tooling

 

  • Visual Studio 2017
  • Postman

Create an ASP.NET core application

Open Visual Studio, select File -> New -> Project, ASP.NET Core Web Application Template and click OK.

Api-project-menu

 

Figure: Project Menu

 

Select an API template as shown in the figure below.

software-architects

 

Figure: Project Menu

 

Then click OK, it will create a new ASP .NET core project with some predefined configuration files and controller.

software-architects

 

Figure: Project Menu

 

The program.cs class which contains the main method with a method called CreatWebhostBuilder () is responsible for running and configuring the application. The host for the application is set with the Startup type as a Startup class.

The Startup.cs class includes two important methods,

ConfigureServices() - Used to create dependency injection containers and add services to configure those services.

Configure () - Used to configure how the ASP.NET core application responds to an individual HTTP request.

Configure the Entity Framework Core

Create a folder called Entities to organize entity model classes. Let's create an entity model class.

Author.cs

namespace API_Demo.Entities
{
[Table("Author",Schema ="dbo")]
public class Author
{
[Key]
public Guid AuthorId { get; set; }
[Required]
[MaxLength(50)]
public string FirstName { get; set; }
[Required]
[MaxLength(50)]
public string LastName { get; set; }
[Required]
[MaxLength(50)]
public string Genre { get; set; }
public ICollection Books { get; set; } = new List();
}
}

Book.cs

namespace API_Demo.Entities
{
[Table("Book", Schema = "dbo")]
public class Book
{
[Key]    
public  Guid BookId { get; set; }
[Required]
[MaxLength(150)]
public string Title { get; set; }
[MaxLength(200)]
public string Description { get; set; }
[ForeignKey("AuthorId")]
public Author Author { get; set; }
public Guid AuthorId { get; set; }
}
}

Creating a context file

Let's create a context file, add a new class file, and name it as LibraryContext.cs.

LibraryContext.cs

namespace API_Demo.Entities
{
public class LibraryContext:DbContext
{
public LibraryContext(DbContextOptions options):base(options)
{
Database.Migrate();
}
public DbSet Authors { get; set; }
public DbSet Books { get; set; }
}
}

Finally, let’s register our context in Startup.cs.

 
namespace API_Demo{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext(op => op.UseSqlServer(Configuration["ConnectionString:BookStoreDB"]));
services.AddScoped, LibraryRepository>();
}

Generate Database from code-first approach

Run and follow command in the Package Manager console.

Add-Migration API_Demo.Entities.LibraryContext

This will create a class for migration. Run the following command to update the database.

Update-database

Sending data

Let's add some data to the author table. For this, we need to override the method of OnModelCreating in the LibraryContact class.

 
namespace API_Demo.Entities
{
public class LibraryContext:DbContext
{
public LibraryContext(DbContextOptions options):base(options)
{
Database.Migrate();
}
public DbSet Authors { get; set; }
public DbSet Books { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity().HasData(new Author
{
AuthorId= Guid.NewGuid(),
FirstName = "nik",
LastName = "rathod",
Genre = "Drama"
}, new Author
{
AuthorId=Guid.NewGuid(),
FirstName = "vivek",
LastName = "rathod",
Genre = "Fantasy"
});
}
}
}

Let's run the migration and update the command once again.

  • 1. Add-Migration API_Demo.Entities.LibraryContextSeed

  • 2. Update-database

Creating a Repository

Let's add a repository folder to apply the repository pattern to access the context method.

Create a two more folders-Contract and Implementation - under the repository folder.

Create the interface ILibraryRepository.cs under the Contract folder.

ILibraryRepository.cs

 
namespace API_Demo.Repository.Contract
{
public interface ILibraryRepository
{
IEnumerable GetAllAuthor();
}
}

Let us create a class under the Implementation folder to execute the function.

LibraryRepository.cs

 
namespace API_Demo.Repository.Implementation
{
public class LibraryRepository: ILibraryRepository
{
readonly LibraryContext _libraryContext;
public LibraryRepository(LibraryContext context)
{
_libraryContext = context;
}
public IEnumerable GetAllAuthor()
{
return _libraryContext.Authors.ToList();
}
}
}

The above method will return a complete list of records from the GetAllAuthor() author table.

Let's configure the repository using dependency injection. Startup.CS Open the file, add the following code to the ConfigurationServices method

 
services.AddScoped, LibraryRepository>();

Searching for Dedicated ASP.Net Core Web Developer ? Your Search ends here.

Create an API Controller

Right-click on the controller and go to Add-> Controller. Simply select the API template and name the controller. We named the controller as Libraries Controller.

Create an API Controller

 

Figure: Add Scaffold

 

LibrariesController.cs

namespace API_Demo.Controllers
{
[Route("api/Libraries")]
[ApiController]
public class LibrariesController : ControllerBase
{
private readonly ILibraryRepository _libraryRepository;
public LibrariesController(ILibraryRepository libraryRepository)
{
 _libraryRepository = libraryRepository;
}
// GET: api/Libraries/GetAllAuthor
[HttpGet]
[Route("GetAllAuthor")]
public IActionResult GetAllAuthor()
{
IEnumerable authors = _libraryRepository.GetAllAuthor();
return Ok(authors);
}
}
}

We have created a web api with an endpoint api/Libraries/GetAllAuthor to retrieve the author list from the database.

Let's test the API using the Postman tool.

Postmen

 

Figure: Postmen

 

Yes, we got the author list in response.

Conclusion

In this article, we have learned about how practically Asp.Net Core API with Entity Framework mechanism works. The approach is simple to learn and believe us once you get familiar with the process and how it works, you can literally play with the development.

ASP.NET CORE API with Entity Framework Table of Content 1. Introduction 2. Overview 3. Tooling 4. Create an ASP.NET core application 5. Configure the Entity Framework Core 6. Creating a context file 7. Generate Database from code-first approach 8. Sending data 9. Creating a Repository 10. Create an API Controller 11.Conclusion Introduction The ASP.NET Core is a free open-source and cross-platform framework for creating cloud-based applications, such as web applications, IoT applications and mobile backends. ASP.NET Core MVC is a middleware that provides a framework for creating APIs and web applications using MVC. HTTP is not just for serving web pages. It is also a powerful platform for creating APIs that reveal services and data. HTTP is simple, flexible and ubiquitous. Most of the platform you can think of has an HTTP library, so HTTP services can reach a wide range of customers, including browsers, mobile devices and traditional desktop applications. ASP .NET Core has built-in support for MVC Building Web API. Integrating the two frameworks makes it easier to create applications that include both UI (HTML) and API, as they now share the same code base and pipeline. Overview Here is the API you created: The following figure shows the basic design of the application. The client is whatever consumes the web API (browser, mobile application and so on). We are not writing clients in this tutorial. The model is an object that represents data in your application. In this case, the only model has to do item. Model are represented as Simple C # Class (POCO). A controller is an object that handles HTTP requests and generates HTTP responses. This application will have a single controller. Tooling   Visual Studio 2017 Postman Create an ASP.NET core application Open Visual Studio, select File -> New -> Project, ASP.NET Core Web Application Template and click OK.   Figure: Project Menu   Select an API template as shown in the figure below.   Figure: Project Menu   Then click OK, it will create a new ASP .NET core project with some predefined configuration files and controller.   Figure: Project Menu   The program.cs class which contains the main method with a method called CreatWebhostBuilder () is responsible for running and configuring the application. The host for the application is set with the Startup type as a Startup class. The Startup.cs class includes two important methods, ConfigureServices() - Used to create dependency injection containers and add services to configure those services. Configure () - Used to configure how the ASP.NET core application responds to an individual HTTP request. Read More: What Is Routing In Asp.Net Core Mvc? Configure the Entity Framework Core Create a folder called Entities to organize entity model classes. Let's create an entity model class. Author.cs namespace API_Demo.Entities { [Table("Author",Schema ="dbo")] public class Author { [Key] public Guid AuthorId { get; set; } [Required] [MaxLength(50)] public string FirstName { get; set; } [Required] [MaxLength(50)] public string LastName { get; set; } [Required] [MaxLength(50)] public string Genre { get; set; } public ICollection Books { get; set; } = new List(); } } Book.cs namespace API_Demo.Entities { [Table("Book", Schema = "dbo")] public class Book { [Key] public Guid BookId { get; set; } [Required] [MaxLength(150)] public string Title { get; set; } [MaxLength(200)] public string Description { get; set; } [ForeignKey("AuthorId")] public Author Author { get; set; } public Guid AuthorId { get; set; } } } Creating a context file Let's create a context file, add a new class file, and name it as LibraryContext.cs. LibraryContext.cs namespace API_Demo.Entities { public class LibraryContext:DbContext { public LibraryContext(DbContextOptions options):base(options) { Database.Migrate(); } public DbSet Authors { get; set; } public DbSet Books { get; set; } } } Finally, let’s register our context in Startup.cs.   namespace API_Demo{ public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } . public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddDbContext(op => op.UseSqlServer(Configuration["ConnectionString:BookStoreDB"])); services.AddScoped, LibraryRepository>(); } Generate Database from code-first approach Run and follow command in the Package Manager console. Add-Migration API_Demo.Entities.LibraryContext This will create a class for migration. Run the following command to update the database. Update-database Sending data Let's add some data to the author table. For this, we need to override the method of OnModelCreating in the LibraryContact class.   namespace API_Demo.Entities { public class LibraryContext:DbContext { public LibraryContext(DbContextOptions options):base(options) { Database.Migrate(); } public DbSet Authors { get; set; } public DbSet Books { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().HasData(new Author { AuthorId= Guid.NewGuid(), FirstName = "nik", LastName = "rathod", Genre = "Drama" }, new Author { AuthorId=Guid.NewGuid(), FirstName = "vivek", LastName = "rathod", Genre = "Fantasy" }); } } } Let's run the migration and update the command once again. 1. Add-Migration API_Demo.Entities.LibraryContextSeed 2. Update-database Creating a Repository Let's add a repository folder to apply the repository pattern to access the context method. Create a two more folders-Contract and Implementation - under the repository folder. Create the interface ILibraryRepository.cs under the Contract folder. ILibraryRepository.cs   namespace API_Demo.Repository.Contract { public interface ILibraryRepository { IEnumerable GetAllAuthor(); } } Let us create a class under the Implementation folder to execute the function. LibraryRepository.cs   namespace API_Demo.Repository.Implementation { public class LibraryRepository: ILibraryRepository { readonly LibraryContext _libraryContext; public LibraryRepository(LibraryContext context) { _libraryContext = context; } public IEnumerable GetAllAuthor() { return _libraryContext.Authors.ToList(); } } } The above method will return a complete list of records from the GetAllAuthor() author table. Let's configure the repository using dependency injection. Startup.CS Open the file, add the following code to the ConfigurationServices method   services.AddScoped, LibraryRepository>(); Searching for Dedicated ASP.Net Core Web Developer ? Your Search ends here. See here Create an API Controller Right-click on the controller and go to Add-> Controller. Simply select the API template and name the controller. We named the controller as Libraries Controller.   Figure: Add Scaffold   LibrariesController.cs namespace API_Demo.Controllers { [Route("api/Libraries")] [ApiController] public class LibrariesController : ControllerBase { private readonly ILibraryRepository _libraryRepository; public LibrariesController(ILibraryRepository libraryRepository) { _libraryRepository = libraryRepository; } // GET: api/Libraries/GetAllAuthor [HttpGet] [Route("GetAllAuthor")] public IActionResult GetAllAuthor() { IEnumerable authors = _libraryRepository.GetAllAuthor(); return Ok(authors); } } } We have created a web api with an endpoint api/Libraries/GetAllAuthor to retrieve the author list from the database. Let's test the API using the Postman tool.   Figure: Postmen   Yes, we got the author list in response. Conclusion In this article, we have learned about how practically Asp.Net Core API with Entity Framework mechanism works. The approach is simple to learn and believe us once you get familiar with the process and how it works, you can literally play with the development.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

A complete guide on eCommerce conversion rate optimization
A complete guide on eCommerce conversion rate optimization

Table of Content 1. Define your goals 2. Know your target audience 3. Simplified UI/UX design, simple navigation, and high resolution images 4. Design a dedicated landing...

Read More
A comprehensive guide on the Construction management software
A comprehensive guide on the Construction management software

Table of Content 1. Mobile compatibility and inventory management 2. Accurately forecast job costs and monitor them 3. STACK 4. On-premises software is better suited...

Read More
Java And Environment Variables: A Brief Overview
Java And Environment Variables: A Brief Overview

Java is one of many programming languages that have shown much promise in the coding world. With that said, there are many components to consider, when working with Java, including...

Read More