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.
Choose an API template as shown in the below figure.
By clicking on OK, it will create a new ASP.NET Core project with some pre-defined configuration files and controller.
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
- [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<Book> Books { get; set; } = new List<Book>();
- }
Book.cs
- 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
- public class LibraryContext:DbContext
- {
- public LibraryContext(DbContextOptions<LibraryContext> options):base(options)
- {
- Database.Migrate();
- }
- public DbSet<Author> Authors { get; set; }
- public DbSet<Book> Books { get; set; }
- }
Let’s define the database connection in the appsettings.json file.
- {
- "Logging": {
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "ConnectionString": {
- "BookStoreDB": "server=server name;database=BookStore;User ID= server user id;password= your server password;"
- },
- "AllowedHosts": "*"
- }
Finally, let’s register our context in Startup.cs.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
- services.AddDbContext<LibraryContext>(op => op.UseSqlServer(Configuration["ConnectionString:BookStoreDB"]));
- }
Generate Database from code-first approach
Run the following command in the Package Manager console.
- Add-Migration MyCoreAPIDemo.Entities.LibraryContext
This will create a class for migration. Run the following command to update the database.
This will update the database based on our models,
Let’s verify that database and tables from server explorer in Visual Studio.
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
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Author>().HasData(new Author
- {
- AuthorId= Guid.NewGuid(),
- FirstName = "Bob",
- LastName = "Ross",
- Genre = "Drama"
-
- }, new Author
- {
- AuthorId=Guid.NewGuid(),
- FirstName = "David",
- LastName = "Miller",
- Genre = "Fantasy"
- });
- }
Let’s run the migration and update command once again.
- Add-Migration MyCoreAPIDemo.Entities.LibraryContextSeed
-
- Update-database
Let’s check the data from server explorer.
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
- public interface ILibraryRepository<T>
- {
- IEnumerable<T> GetAllAuthor();
- }
Let’s create a class under implementation folder to implement the function.
LibraryRepository.cs
- public class LibraryRepository: ILibraryRepository<Author>
- {
- readonly LibraryContext _libraryContext;
-
- public LibraryRepository(LibraryContext context)
- {
- _libraryContext = context;
- }
-
- public IEnumerable<Author> GetAllAuthor()
- {
- return _libraryContext.Authors.ToList();
- }
- }
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.
- 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.
LibrariesController.cs
- [Route("api/Libraries")]
- [ApiController]
- public class LibrariesController : ControllerBase
- {
- private readonly ILibraryRepository<Author> _libraryRepository;
-
- public LibrariesController(ILibraryRepository<Author> libraryRepository)
- {
- _libraryRepository = libraryRepository;
- }
-
-
- [HttpGet]
- [Route("GetAllAuthor")]
- public IActionResult GetAllAuthor()
- {
- IEnumerable<Author> authors = _libraryRepository.GetAllAuthor();
- return Ok(authors);
- }
-
- }
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.
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.