DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Empowering Real-World Solutions the Synergy of AI and .NET
  • New ORM Framework for Kotlin
  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Multi-Tenancy and Its Improved Support in Hibernate 6.3.0

Trending

  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Automatic Code Transformation With OpenRewrite
  • Integrating Security as Code: A Necessity for DevSecOps
  • A Complete Guide to Modern AI Developer Tools
  1. DZone
  2. Coding
  3. Frameworks
  4. CRUD Operation Using Entity Framework Core and Stored Procedure in .Net Core 6 Web API

CRUD Operation Using Entity Framework Core and Stored Procedure in .Net Core 6 Web API

A step-by-step tutorial on the CRUD operation implementation of Web API using entity framework core and stored procedure with guide pictures and code.

By 
Jaydeep Patil user avatar
Jaydeep Patil
·
Oct. 27, 22 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
5.8K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we are going to discuss the implementation of Web API using entity framework core and stored procedure.

Prerequisites

  1. .NET Core SDK 6
  2. SQL Server 
  3. Visual Studio 2022

Agenda

  • Implementation of .NET Core 6 Web API
  • Implementation of stored procedures

Implementation of .NET Core 6 Web API

Step 1

Create a new .NET Core Web API application.

New Net Core Web API

Step 2

Configure the application.

Configure New Project

Step 3

Provide additional information.

Additional Information

Step 4

Project structure

Project Structure

Step 5

Create a product class inside the "Entities" folder.

C#
 
using System.ComponentModel.DataAnnotations;



namespace EntityFrameworkSP_Demo.Entities

{

    public class Product

    {

        public int ProductId { get; set; }

        public string ProductName { get; set; }

        public string ProductDescription { get; set; }

        public int ProductPrice { get; set; }

        public int ProductStock { get; set; }

    }

}


Step 6

Add a new DbContextClass inside the "Data" folder.

C#
 
using EntityFrameworkSP_Demo.Entities;

using Microsoft.EntityFrameworkCore;



namespace EntityFrameworkSP_Demo.Data

{

    public class DbContextClass : DbContext

    {

        protected readonly IConfiguration Configuration;



        public DbContextClass(IConfiguration configuration)

        {

            Configuration = configuration;

        }

        protected override void OnConfiguring(DbContextOptionsBuilder options)

        {

            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));

        }



        public DbSet<Product> Product { get; set; }

    }

}


Step 7

Create IProductService and ProductService inside the "Repositories" folder.

IProductService:

C#
 
using EntityFrameworkSP_Demo.Entities;



namespace EntityFrameworkSP_Demo.Repositories

{

    public interface IProductService

    {

        public Task<List<Product>> GetProductListAsync();

        public Task<IEnumerable<Product>> GetProductByIdAsync(int Id);

        public Task<int> AddProductAsync(Product product);

        public Task<int> UpdateProductAsync(Product product);

        public Task<int> DeleteProductAsync(int Id);

    }

}


ProductService:

C#
 
using EntityFrameworkSP_Demo.Data;

using EntityFrameworkSP_Demo.Entities;

using Microsoft.Data.SqlClient;

using Microsoft.EntityFrameworkCore;



namespace EntityFrameworkSP_Demo.Repositories

{

    public class ProductService : IProductService

    {

        private readonly DbContextClass _dbContext;



        public ProductService(DbContextClass dbContext)

        {

            _dbContext = dbContext;

        }



        public async Task<List<Product>> GetProductListAsync()

        {

            return await _dbContext.Product

                .FromSqlRaw<Product>("GetPrductList")

                .ToListAsync();

        }



        public async Task<IEnumerable<Product>> GetProductByIdAsync(int ProductId)

        {

            var param = new SqlParameter("@ProductId", ProductId);



            var productDetails = await Task.Run(() => _dbContext.Product

                            .FromSqlRaw(@"exec GetPrductByID @ProductId", param).ToListAsync());



            return productDetails;

        }



        public async Task<int> AddProductAsync(Product product)

        {

            var parameter = new List<SqlParameter>();

            parameter.Add(new SqlParameter("@ProductName", product.ProductName));

            parameter.Add(new SqlParameter("@ProductDescription", product.ProductDescription));

            parameter.Add(new SqlParameter("@ProductPrice", product.ProductPrice));

            parameter.Add(new SqlParameter("@ProductStock", product.ProductStock));



            var result = await Task.Run(() =>  _dbContext.Database

           .ExecuteSqlRawAsync(@"exec AddNewProduct @ProductName, @ProductDescription, @ProductPrice, @ProductStock", parameter.ToArray()));



            return result;

        }



        public async Task<int> UpdateProductAsync(Product product)

        {

            var parameter = new List<SqlParameter>();

            parameter.Add(new SqlParameter("@ProductId", product.ProductId));

            parameter.Add(new SqlParameter("@ProductName", product.ProductName));

            parameter.Add(new SqlParameter("@ProductDescription", product.ProductDescription));

            parameter.Add(new SqlParameter("@ProductPrice", product.ProductPrice));

            parameter.Add(new SqlParameter("@ProductStock", product.ProductStock));



            var result = await Task.Run(() => _dbContext.Database

            .ExecuteSqlRawAsync(@"exec UpdateProduct @ProductId, @ProductName, @ProductDescription, @ProductPrice, @ProductStock", parameter.ToArray()));

            return result;

        }

        public async Task<int> DeleteProductAsync(int ProductId)

        {

            return await Task.Run(() => _dbContext.Database.ExecuteSqlInterpolatedAsync($"DeletePrductByID {ProductId}"));

        }

    }

}


FromSqlRawmethod is used to execute SQL commands against the database and returns the instance of DbSet.

ExecuteSqlRawAsyncis used to execute the SQL commands and returns the number of rows affected.

ExecuteSqlInterpolatedAsyncexecutes SQL command and returns the number of affected rows.

Step 8

Add database connection string inside the appsettings.json file.

JSON
 
{

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft.AspNetCore": "Warning"

    }

  },

  "AllowedHosts": "*",

  "ConnectionStrings": {

    "DefaultConnection": "Data Source=DESKTOP;Initial Catalog=StoredProcedureEFDemo;User Id=sa;Password=database;"

  }

}


Step 9

Register services inside the program class.

C#
 
using EntityFrameworkSP_Demo.Data;

using EntityFrameworkSP_Demo.Repositories;



var builder = WebApplication.CreateBuilder(args);



// Add services to the container.

builder.Services.AddScoped<IProductService, ProductService>();

builder.Services.AddDbContext<DbContextClass>();



builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();



var app = builder.Build();



// Configure the HTTP request pipeline.

if (app.Environment.IsDevelopment())

{

    app.UseSwagger();

    app.UseSwaggerUI();

}



app.UseAuthorization();



app.MapControllers();



app.Run();


Step 10

Create a new product controller.

C#
 
using EntityFrameworkSP_Demo.Entities;

using EntityFrameworkSP_Demo.Repositories;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using System.Collections.Generic;



namespace EntityFrameworkSP_Demo.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class ProductsController : ControllerBase

    {

        private readonly IProductService productService;



        public ProductsController(IProductService productService)

        {

            this.productService = productService;

        }



        [HttpGet("getproductlist")]

        public async Task<List<Product>> GetProductListAsync()

        {

            try

            {

                return await productService.GetProductListAsync();

            }

            catch

            {

                throw;

            }

        }



        [HttpGet("getproductbyid")]

        public async Task<IEnumerable<Product>> GetProductByIdAsync(int Id)

        {

            try

            {

                var response = await productService.GetProductByIdAsync(Id);



                if(response == null)

                {

                    return null;

                }



                return response;

            }

            catch

            {

                throw;

            }

        }



        [HttpPost("addproduct")]

        public async Task<IActionResult> AddProductAsync(Product product)

        {

            if(product == null)

            {

                return BadRequest();

            }



            try

            {

                var response = await productService.AddProductAsync(product);



                return Ok(response);

            }

            catch

            {

                throw;

            }

        }



        [HttpPut("updateproduct")]

        public async Task<IActionResult> UpdateProductAsync(Product product)

        {

            if (product == null)

            {

                return BadRequest();

            }



            try

            {

                var result =  await productService.UpdateProductAsync(product);

                return Ok(result);

            }

            catch

            {

                throw;

            }

        }



        [HttpDelete("deleteproduct")]

        public async Task<int> DeleteProductAsync(int Id)

        {

            try

            {

                var response = await productService.DeleteProductAsync(Id);

                return response;

            }

            catch

            {

                throw;

            }

        }

    }

}


Step 11

Execute the following command to create migration and update the database in the package manager console.

add-migration "Initial"

update-database

Step 12

Implementation of stored procedures

GetPrductList:

SQL
 
USE [StoredProcedureEFDemo]

GO



/****** Object:  StoredProcedure [dbo].[GetPrductList]    Script Date: 10/16/2022 11:08:29 AM ******/

SET ANSI_NULLS ON

GO



SET QUOTED_IDENTIFIER ON

GO



CREATE OR ALTER PROCEDURE [dbo].[GetPrductList]

AS

BEGIN

    SELECT * FROM dbo.Product

END

GO


GetPrductByID:

SQL
 
USE [StoredProcedureEFDemo]

GO



/****** Object:  StoredProcedure [dbo].[GetPrductByID]    Script Date: 10/16/2022 11:09:04 AM ******/

SET ANSI_NULLS ON

GO



SET QUOTED_IDENTIFIER ON

GO



CREATE OR ALTER PROCEDURE [dbo].[GetPrductByID]

@ProductId int

AS

BEGIN

    SELECT

        ProductId,

        ProductName,

        ProductDescription,

        ProductPrice,

        ProductStock

    FROM dbo.Product where ProductId = @ProductId

END

GO


AddNewProduct:

SQL
 
USE [StoredProcedureEFDemo]

GO



/****** Object:  StoredProcedure [dbo].[AddNewProduct]    Script Date: 10/16/2022 11:09:20 AM ******/

SET ANSI_NULLS ON

GO



SET QUOTED_IDENTIFIER ON

GO





CREATE OR ALTER PROCEDURE [dbo].[AddNewProduct]

@ProductName [nvarchar](max),

@ProductDescription [nvarchar](max),

@ProductPrice int,

@ProductStock int

AS

BEGIN

    INSERT INTO dbo.Product

        (

            ProductName,

            ProductDescription,

            ProductPrice,

            ProductStock

        )

    VALUES

        (

            @ProductName,

            @ProductDescription,

            @ProductPrice,

            @ProductStock

        )

END

GO


UpdateProduct:

SQL
 
USE [StoredProcedureEFDemo]
GO

/****** Object:  StoredProcedure [dbo].[UpdateProduct]    Script Date: 10/16/2022 11:09:38 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [dbo].[UpdateProduct]
@ProductId int,
@ProductName [nvarchar](max),
@ProductDescription [nvarchar](max),
@ProductPrice int,
@ProductStock int
AS
BEGIN
	UPDATE dbo.Product
    SET
		ProductName = @ProductName,
		ProductDescription = @ProductDescription,
		ProductPrice = @ProductPrice,
		ProductStock = @ProductStock
	WHERE ProductId = @ProductId
END
GO


DeletePrductByID:

SQL
 
USE [StoredProcedureEFDemo]

GO



/****** Object:  StoredProcedure [dbo].[DeletePrductByID]    Script Date: 10/16/2022 11:09:50 AM ******/

SET ANSI_NULLS ON

GO



SET QUOTED_IDENTIFIER ON

GO



CREATE OR ALTER PROCEDURE [dbo].[DeletePrductByID]

@ProductId int

AS

BEGIN

    DELETE FROM dbo.Product where ProductId = @ProductId

END

GO


Step 13

Finally, run the application:

Run Application


http://localhost:5002/api/Products/getproductlist

Get Product List

http://localhost:5002/api/Products/getproductbyid?Id=16

Get Product ID

http://localhost:5002/api/Products/addproduct

Add Product

http://localhost:5002/api/Products/updateproduct

Update Product

http://localhost:5002/api/Products/deleteproduct?Id=19

Delete Product

 The GitHub repository for this tutorial is available here.

Conclusion

Here we discussed the implementation of Web API using Entity Framework Core and stored procedure.

Happy learning!

API Entity Framework Web API Framework Net (command) Data Types

Published at DZone with permission of Jaydeep Patil. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Empowering Real-World Solutions the Synergy of AI and .NET
  • New ORM Framework for Kotlin
  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Multi-Tenancy and Its Improved Support in Hibernate 6.3.0

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!