×

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.

Ready to take your ASP.NET Core API to the next level? Explore our comprehensive API development and integration services to enhance performance and scalability. Contact us today to discuss your project!

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 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. Ready to take your ASP.NET Core API to the next level? Explore our comprehensive API development and integration services to enhance performance and scalability. Contact us today to discuss your project! 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.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

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

Power Apps Solving 13 Legal Challenges
Power Apps Solving 13 Legal Challenges

There is a common misconception that bringing technology into the legal field won't be effective as this profession relies heavily on evidence and facts. However, if you look at it...

How to Automate Power BI Reports Using Power Automate
How to Automate Power BI Reports Using Power Automate

"Does Power Automate work with Power BI?”. If you think the same, you’re at the right place. Manual reporting plays an important role in business decision-making but requires more...

What’s New in .NET 9?
What’s New in .NET 9?

Today, we’re thrilled to present you with the first glimpse of .NET 9 release and let you know what features and updates you can anticipate in this new version. Various professionals believe that it’s the right time to explore and adopt the latest version of .NET for your upcoming projects. It is even recommended for projects built using .NET 6 or .NET 8, due to the framework updates made in this version.