×

iFour Logo

ASP.NET CORE API with Entity Framework

Kapil Panchal - November 20, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
ASP.NET CORE API with Entity Framework

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.

 

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.

 

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.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Next-Gen Programming Languages: Shaping the Future of Software Development in 2024
Next-Gen Programming Languages: Shaping the Future of Software Development in 2024

Introduction Imagine standing in line at the grocery store, waiting to pay for groceries. You pull out your phone and scan each item’s barcode with a single tap. This seemingly...

MySQL vs Azure SQL Database: Understanding Needs, Factors, and Performance Metrics
MySQL vs Azure SQL Database: Understanding Needs, Factors, and Performance Metrics

The world of technology is constantly changing, and databases are at the forefront of this evolution. We have explored different types of databases, both physical and cloud-based, and realized how each of them provides unique features to improve data accessibility and inclusive performance. Leading the pack are MySQL and Azure SQL database services , helping business elevate their processes to new heights.

Streamlining E-commerce Operations with Microsoft PowerApps
Streamlining E-commerce Operations with Microsoft PowerApps

In today's rapidly changing digital world, eCommerce is a dynamic industry. Every day, millions of transactions take place online, so companies are always looking for new and creative methods to improve consumer satisfaction and optimize operations.