Crud operations using stored procedure and entity framework in asp.net core


In this article, we will discuss how to perform CRUD operations using stored procedures and Entity Framework in ASP.NET Core. We will delve into all the necessary steps in detail, enabling you to write your own code easily. Perform insert, update, and delete operations on a customer table using stored procedures in ASP.NET MVC. 
 Below is an example demonstrating how to perform insert, update, and delete operations on a customer table using stored procedures in ASP.NET MVC. This assumes you have a Customer model and a CustomerDbContext
 Model:
// Customer.cs
public class Customer
{
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }    
}
DbContext:
// CustomerDbContext.cs
public class CustomerDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }

    // Other DbContext configurations

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Configure your database connection
        optionsBuilder.UseSqlServer("connection_string");
    }
}
Replace "connection_string" with your actual database connection string. Stored Procedures: Create stored procedures in your database for insert, update, and delete operations.
-- Example of a stored procedure for inserting a customer
CREATE PROCEDURE InsertCustomer
    @FirstName NVARCHAR(50),
    @LastName NVARCHAR(50)
AS
BEGIN
    INSERT INTO Customers (FirstName, LastName)
    VALUES (@FirstName, @LastName)
END

-- Example of a stored procedure for updating a customer
CREATE PROCEDURE UpdateCustomer
    @CustomerId INT,
    @FirstName NVARCHAR(50),
    @LastName NVARCHAR(50)
AS
BEGIN
    UPDATE Customers
    SET FirstName = @FirstName, LastName = @LastName
    WHERE CustomerId = @CustomerId
END

-- Example of a stored procedure for deleting a customer
CREATE PROCEDURE DeleteCustomer
    @CustomerId INT
AS
BEGIN
    DELETE FROM Customers
    WHERE CustomerId = @CustomerId
END
Controller: 
Create an MVC controller to handle HTTP requests and interact with the database.
// CustomerController.cs
public class CustomerController : Controller
{
    private readonly CustomerDbContext _context;

    public CustomerController(CustomerDbContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        var customers = _context.Customers.ToList();
        return View(customers);
    }

    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Create(Customer customer)
    {
        if (ModelState.IsValid)
        {
            _context.Database.ExecuteSqlRaw("EXEC InsertCustomer @p0, @p1", customer.FirstName, customer.LastName);
            return RedirectToAction("Index");
        }

        return View(customer);
    }

    public IActionResult Edit(int id)
    {
        var customer = _context.Customers.Find(id);
        return View(customer);
    }

    [HttpPost]
    public IActionResult Edit(Customer customer)
    {
        if (ModelState.IsValid)
        {
            _context.Database.ExecuteSqlRaw("EXEC UpdateCustomer @p0, @p1, @p2", customer.CustomerId, customer.FirstName, customer.LastName);
            return RedirectToAction("Index");
        }

        return View(customer);
    }

    public IActionResult Delete(int id)
    {
        var customer = _context.Customers.Find(id);
        return View(customer);
    }

    [HttpPost, ActionName("Delete")]
    public IActionResult DeleteConfirmed(int id)
    {
        _context.Database.ExecuteSqlRaw("EXEC DeleteCustomer @p0", id);
        return RedirectToAction("Index");
    }
}
This example demonstrates the basic structure of an ASP.NET MVC application performing CRUD operations on a Customer table using stored procedures. Adjust the code based on your specific requirements, validation needs, and error handling. 

Below is the view code for performing the create, edit, delete, and index actions in ASP.NET MVC. Create separate views for each action within the "Views/Customer" folder. 
Create View (Create.cshtml):
@model TestProject.Customer

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>
      
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
Edit View (Edit.cshtml):
@model TestProject.Customer

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.CustomerId)

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
Delete View (Delete.cshtml):
@model TestProject.Customer

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Customer</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.FirstName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.LastName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.LastName)
        </dd>       
    </dl>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <input type="submit" value="Delete" class="btn btn-danger" />
    }

    @Html.ActionLink("Back to List", "Index")
</div>
Index View (Index.cshtml):
@model IEnumerable<TestProject.Customer>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>         
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.CustomerId }) |
                @Html.ActionLink("Details", "Details", new { id = item.CustomerId }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.CustomerId })
            </td>
        </tr>
    }
</table>
Replace "TestProject" with the actual namespace of your application. These views are basic examples, and you may need to adjust them based on your specific styling, validation, and functionality requirements.