Create an ASP.NET Core Web API CRUD Operations using Database-First approach also consume in .net core app
In ASP.NET Core Web API, using the Database-First approach allows you to generate models based on an existing database. Here's a step-by-step guide to building a CRUD application using this approach.
Prerequisites:
- Visual Studio 2022 or later
- SQL Server with an existing database
- Entity Framework Core installed (can be added via NuGet)
Steps to create an ASP.NET Core Web API using Database-First approach:
1. Create a New ASP.NET Core Web API Project
- Open Visual Studio.
- Go to File > New > Project.
- Select ASP.NET Core Web API and click Next.
- Name your project (e.g.,
WebApiCRUD
) and click Create. - Select .NET 7.0 or .NET 6.0 as the framework and choose the template API.
2. Install Entity Framework Core Packages
In NuGet Package Manager or Package Manager Console, install the following packages:
3. Generate Models from an Existing Database
In the Package Manager Console, run the following command to scaffold your models based on an existing database:
- Replace
YourConnectionString
with the actual connection string of your database. - The
-OutputDir Models
option specifies the folder where your models andDbContext
will be generated.
This command will generate all the database tables as Entity Framework models and create a DbContext class that represents your database.
4. Create a Controller for CRUD Operations
Once the models and DbContext
are generated, you can create a controller to perform CRUD operations.
Example: Creating a CRUD Controller for an Employee
Entity
- Add a new controller:
- Right-click on the Controllers folder.
- Select Add > Controller > API Controller with actions, using Entity Framework.
- Select your model (e.g.,
Employee
) andDbContext
(e.g.,YourDbContext
).
This will automatically generate a controller with all the CRUD operations (GET, POST, PUT, DELETE).
5. CRUD Methods
The generated controller will include the following actions:
a) GET All Records
b) GET Single Record by ID
c) POST (Create) a New Record
d) PUT (Update) a Record
e) DELETE a Record
6. Test the API Using Postman or Swagger
- Swagger is built into ASP.NET Core by default, so you can test your API directly from the browser.
- Launch the project, and navigate to
https://localhost:<port>/swagger
. You will see a UI where you can test all the CRUD operations.
Alternatively, you can use Postman for testing by making GET, POST, PUT, and DELETE requests to the appropriate API endpoints.
7. Connection String Configuration
Ensure your connection string is set up in the appsettings.json
:
In the Startup.cs
(or Program.cs
in .NET 6/7), register the DbContext:
That's it!
You now have a functional ASP.NET Core Web API using the Database-First approach.
Consume the Web API in a .NET Core Application
No comments: