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.
Select an API template as shown in the figure below.
Then click OK, it will create a new ASP .NET core project with some predefined configuration files and controller.
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.
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<book> Books { get; set; } = new List<book>();
}
}</book></book>
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<librarycontext> options):base(options)
{
Database.Migrate();
}
public DbSet<author> Authors { get; set; }
public DbSet<book> Books { get; set; }
}
}
</book></author></librarycontext>
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<librarycontext>(op => op.UseSqlServer(Configuration["ConnectionString:BookStoreDB"]));
services.AddScoped<ilibraryrepository<author>, LibraryRepository>();
}
</ilibraryrepository<author></librarycontext>
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<librarycontext> options):base(options)
{
Database.Migrate();
}
public DbSet<author> Authors { get; set; }
public DbSet<book> Books { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<author>().HasData(new Author
{
AuthorId= Guid.NewGuid(),
FirstName = "nik",
LastName = "rathod",
Genre = "Drama"
}, new Author
{
AuthorId=Guid.NewGuid(),
FirstName = "vivek",
LastName = "rathod",
Genre = "Fantasy"
});
}
}
}</author></book></author></librarycontext>
Let's run the migration and update the command once again.
Add-Migration API_Demo.Entities.LibraryContextSeed
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<t>
{
IEnumerable<t> GetAllAuthor();
}
}</t></t>
Let us create a class under the Implementation folder to execute the function.
LibraryRepository.cs
namespace API_Demo.Repository.Implementation
{
public class LibraryRepository: ILibraryRepository<author>
{
readonly LibraryContext _libraryContext;
public LibraryRepository(LibraryContext context)
{
_libraryContext = context;
}
public IEnumerable<author> GetAllAuthor()
{
return _libraryContext.Authors.ToList();
}
}
}</author></author>
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<ilibraryrepository<author>, LibraryRepository>();
</ilibraryrepository<author>
Searching for Dedicated .Net 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.
LibrariesController.cs
namespace API_Demo.Controllers
{
[Route("api/Libraries")]
[ApiController]
public class LibrariesController : ControllerBase
{
private readonly ILibraryRepository<author> _libraryRepository;
public LibrariesController(ILibraryRepository<author> libraryRepository)
{
_libraryRepository = libraryRepository;
}
// GET: api/Libraries/GetAllAuthor
[HttpGet]
[Route("GetAllAuthor")]
public IActionResult GetAllAuthor()
{
IEnumerable<author> authors = _libraryRepository.GetAllAuthor();
return Ok(authors);
}
}
}</author></author></author>
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.
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.
Top comments (1)
Please take care of your code formatting. Makes it hard to read and you have some typos in there. E.g. this:
</author></author></author>
in the last Controller. Your Post is not totally bad but could take some review before posting.