In Focus

Create RESTful API Using ASP.NET Core With Entity Framework Core

From this article, you will learn how to create a RESTful API using ASP.NET Core with Entity Framework Core.

Introduction

 
REST

Representational State Transfer is an architectural style where we use a standard to implement it.
 
The browser is an HTTP client. While it points to any URI, it sends the HTTP request to the server. The server will process it and send back the HTTP Response which contains the representation of the page, probably it can be HTML, JSON or XML and many more media types, based on the response the browser will change its state. The client changes its state depending on the representation of the resource which is accessed is called as representational state transfer or REST.

ASP.NET Core
 
ASP.NET Core is an open source, cross-platform framework for building modern internet connected applications, click here to learn more about ASP.NET Core. ASP.NET Core MVC is a middleware which provides a framework for building the APIs and web application using MVC pattern

Tooling
  • Visual Studio 2017 
  • Postman
Download the latest Version of .NET CORE. Currently, I used ASP.NET Core 2.2 to develop the application. 
 

Create an ASP.NET Core application


Open Visual Studio, File -> New ->Project, select ASP.NET Core web application template and click OK.
 
Create RESTful API using ASP.NET Core with Entity Framework CoreCreate RESTful API Using ASP.NET Core With Entity Framework Core
 
Choose an API template as shown in the below figure.

Create RESTful API using ASP.NET Core with Entity Framework CoreCreate RESTful API Using ASP.NET Core With Entity Framework Core
 
By clicking on OK, it will create a new ASP.NET Core project with some pre-defined configuration files and controller.
 
 Create RESTful API using ASP.NET Core with Entity Framework CoreCreate RESTful API Using ASP.NET Core With Entity Framework Core
 
The program.cs class which contains the main method with a method called Createwebhostbuilder(), is responsible for running and configuring the application. The host for the application is set up with the startup type as startup class.
 
The startup.cs class contains two important methods,
 
ConfigureServices() - it is used to add service to build dependency injection containers and configure those services,
Configure() - it is used to configure how the ASP.NET Core application will response to an individual HTTP request.

 
Configure the Entity Framework Core


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

Author.cs 
  1. [Table("Author",Schema ="dbo")]  
  2. public class Author  
  3. {  
  4.     [Key]  
  5.       
  6.     public Guid AuthorId { getset; }  
  7.   
  8.     [Required]  
  9.     [MaxLength(50)]  
  10.     public string FirstName { getset; }  
  11.     [Required]  
  12.     [MaxLength(50)]  
  13.     public string LastName { getset; }  
  14.   
  15.     [Required]  
  16.     [MaxLength(50)]  
  17.     public string Genre { getset; }  
  18.   
  19.     public ICollection<Book> Books { getset; } = new List<Book>();  
  20. }  
Book.cs 
  1. public class Book  
  2. {  
  3.     [Key]  
  4.     public  Guid BookId { getset; }  
  5.     [Required]  
  6.     [MaxLength(150)]  
  7.     public string Title { getset; }  
  8.     [MaxLength(200)]  
  9.     public string Description { getset; }  
  10.   
  11.     [ForeignKey("AuthorId")]  
  12.     public Author Author { getset; }  
  13.   
  14.     public Guid AuthorId { getset; }  
  15.   
  16. }  

Creating a context file

 
Let’s create a context file, add a new class file, and name it as LibraryContext.cs.
 
LibraryContext.cs
  1.   public class LibraryContext:DbContext  
  2.         {  
  3.         public LibraryContext(DbContextOptions<LibraryContext> options):base(options)  
  4.         {  
  5.             Database.Migrate();  
  6.         }  
  7.         public DbSet<Author> Authors { getset; }  
  8.         public DbSet<Book> Books { getset; }  
  9. }  
Let’s define the database connection in the appsettings.json file.
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Warning"  
  5.     }  
  6.   },  
  7.   "ConnectionString": {  
  8.     "BookStoreDB""server=server name;database=BookStore;User ID= server user id;password= your server password;"  
  9.   },  
  10.   "AllowedHosts""*"  
  11. }  
Finally, let’s register our context in Startup.cs.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);  
  4.     services.AddDbContext<LibraryContext>(op => op.UseSqlServer(Configuration["ConnectionString:BookStoreDB"]));  
  5. }  
Generate Database from code-first approach
 
Run the following command in the Package Manager console.
  1. Add-Migration MyCoreAPIDemo.Entities.LibraryContext  
This will create a class for migration. Run the following command to update the database.
  1. Update-database   
This will update the database based on our models,

Let’s verify that database and tables from server explorer in Visual Studio.
 
 Create RESTful API using ASP.NET Core with Entity Framework CoreCreate RESTful API Using ASP.NET Core With Entity Framework Core
 
From the above image, you can notice the tables are created based on our model.
 
Seeding data
 
Let’s add some data to the Author table. For this, we need to override a method OnModelCreating in the LibraryContext class.
 
LibraryContext.cs  
  1. protected override void OnModelCreating(ModelBuilder modelBuilder)  
  2. {  
  3.     modelBuilder.Entity<Author>().HasData(new Author  
  4.     {           
  5.         AuthorId= Guid.NewGuid(),  
  6.         FirstName = "Bob",  
  7.         LastName = "Ross",  
  8.         Genre = "Drama"  
  9.   
  10.     }, new Author  
  11.     {  
  12.         AuthorId=Guid.NewGuid(),  
  13.         FirstName = "David",  
  14.         LastName = "Miller",  
  15.         Genre = "Fantasy"  
  16.     });  
  17. }  
Let’s run the migration and update command once again.
  1. Add-Migration MyCoreAPIDemo.Entities.LibraryContextSeed  
  2.       
  3. Update-database   
Let’s check the data from server explorer.
 
 Create RESTful API using ASP.NET Core with Entity Framework CoreCreate RESTful API Using ASP.NET Core With Entity Framework Core

From the above image, you can notice we got the data in the table based on our update from code.
 

Creating a Repository 

 
Let’s add a repository folder to implement the repository pattern to access the context method.
 
Create two more folders - Contract and Implementation - under the repository folder.
 
Create an interface ILibraryRepository.cs under Contract folder.
 
ILibraryRepository.cs
  1. public interface ILibraryRepository<T>  
  2. {  
  3.     IEnumerable<T> GetAllAuthor();
  4. }  
Let’s create a class under implementation folder to implement the function.
 
LibraryRepository.cs 
  1. public class LibraryRepository: ILibraryRepository<Author>  
  2. {  
  3.     readonly LibraryContext _libraryContext;  
  4.   
  5.     public LibraryRepository(LibraryContext context)  
  6.     {  
  7.         _libraryContext = context;  
  8.     }  
  9.   
  10.     public IEnumerable<Author> GetAllAuthor()  
  11.     {  
  12.         return _libraryContext.Authors.ToList();  
  13.     }  
  14. }  
The above method GetAllAuthor() will return the complete list of records from Author table.
 
Let’s configure the repository using dependency injection. Open Startup.cs file, add the below code in ConfigurationServices method.
  1. services.AddScoped<ILibraryRepository<Author>, LibraryRepository>();  

Create API Controller  

 
Right-click on controller and go to Add->Controller. Choose an empty API template and name the controller. I named the controller as LibrariesController.
 
 Create RESTful API using ASP.NET Core with Entity Framework CoreCreate RESTful API Using ASP.NET Core With Entity Framework Core
 
LibrariesController.cs
  1. [Route("api/Libraries")]  
  2.  [ApiController]  
  3.  public class LibrariesController : ControllerBase  
  4.  {  
  5.      private readonly ILibraryRepository<Author> _libraryRepository;  
  6.   
  7.      public LibrariesController(ILibraryRepository<Author> libraryRepository)  
  8.      {  
  9.          _libraryRepository = libraryRepository;  
  10.      }  
  11.   
  12.      // GET: api/Libraries/GetAllAuthor  
  13.      [HttpGet]  
  14.      [Route("GetAllAuthor")]  
  15.      public IActionResult GetAllAuthor()  
  16.      {  
  17.          IEnumerable<Author> authors = _libraryRepository.GetAllAuthor();  
  18.          return Ok(authors);  
  19.      }  
  20.   
  21.  }  
Yes, we have created a WEB API with an endpoint api/Libraries/GetAllAuthor to get an author list from the database.
 

Let’s test the API using Postman tool.

 Create RESTful API using ASP.NET Core with Entity Framework CoreCreate RESTful API Using ASP.NET Core With Entity Framework Core
 
Yes, we got an author list as a response.
 
Click here to get the source code.
 

Conclusion

 
We have seen how to create a REST API using the ASP.NET Core with Entity Framework core, will see how to create a CRUD APIs using ASP.NET Core in my future article.