Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8901

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T05:25:08+00:00 2024-11-28T05:25:08+00:00

ASP.NET CORE API with Entity Framework

  • 60k

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.

Image description

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.

Image description
Figure: Project Menu

Select an API template as shown in the figure below.

Image description

Then click OK, it will create a new ASP .NET core project with some predefined configuration files and controller.

Image description

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>  
Enter fullscreen mode Exit fullscreen mode

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; } } }  
Enter fullscreen mode Exit fullscreen mode

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>  
Enter fullscreen mode Exit fullscreen mode

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>  
Enter fullscreen mode Exit fullscreen mode

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>  
Enter fullscreen mode Exit fullscreen mode

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<t> { IEnumerable<t> GetAllAuthor(); } }</t></t>  
Enter fullscreen mode Exit fullscreen mode

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>  
Enter fullscreen mode Exit fullscreen mode

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>  
Enter fullscreen mode Exit fullscreen mode

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.

Image description

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>  
Enter fullscreen mode Exit fullscreen mode

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.

Image description

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.

apiaspnetprogrammingwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.