Search This Blog

Thursday 28 December 2017

CRUD Operations in MVC Using Entity Framework

Step 1:- Open Visual Studio 2015 => Goto File Menu => New => Project...

Step 2:- In the Installed Templates list, select Visual C# => Web

Step 3:- Select ASP.Net Web Application from the Web list => Type MvcCRUDWithEntity in the Name box and click OK

Step 4:- Select Empty template from ASP.NET Templates List and Checked MVC check box under Add folders and core references for:



Step 5:- Right-click App_Data folder in Solution Explorer => Add => Click New Items...

Step 6:- Select SQL Server Database from the Data list = > Type ProductDatabase.mdf in the Name box and click OK



Step 7:- Double-click ProductDatabase.mdf in Solution Explorer to open ProductDatabase



Step 8:- Right-click Tables folder => Click Add New Table

Step 9:- Copy Past following Script

CREATE TABLE [dbo].[Product] (
    [ProductId]     INT IDENTITY (1, 1) NOT NULL,
    [ProductName]   VARCHAR (50)    NOT NULL,
    [ProductCode]   VARCHAR (50)    NOT NULL,
    [ProductQty]    INT             NOT NULL,
    [ProductWeight] DECIMAL (18, 2) NOT NULL,
    [ProductDesc]   VARCHAR (500)   NULL,
    PRIMARY KEY CLUSTERED ([ProductId] ASC)
);



Step 10:- Click Update => Click Update Database




Step 11:- Open Server Explorer => Right-click Tables folder => Click Refresh => Expand Tables folder



Step 12:- Right-click Models folder in Solution Explorer => Add => Click New Items...

Step 13:- Select ADO.NET Entity Data Model from the Data list = > Type ProductDataEntity in the Name box and click Add



Step 14:- Select EF Designer from database => Click Next


Step 15:- Click Next => Select Entity Framework 6.x Radio button => Click Next



Step 16:- Expand Tables => Checked Product check box => Click Finish



Step 17:- Right-click Controllers folder in Solution Explorer => Add => Click Controllers...

Step 18:- Select MVC 5 Controller - Empty from the controller list = > Click Add


Step 19:- Type ProductController in the Controller name box and click Add

To perform CRUD operation using Entity Framework, basic activity done successfully. Now implement the CRUD functionality in Product Controller step by step.

Step 1:- Add following Action method in Product Controller

ProductDatabaseEntities prodDatabaseEntities = null;
// GET: Products
public ActionResult Select()
{
            prodDatabaseEntities = new ProductDatabaseEntities();
            List<Product> list = new List<Product>();
            list = prodDatabaseEntities.Products.ToList();
            return View(list);
}

// GET: Create
[HttpGet]
public ActionResult Create()
{
            return View();
}

// POST: Create
 [HttpPost]
 [ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ProductName,ProductCode,ProductQty,ProductWeight,ProductDesc")] Product p)
{
            if (ModelState.IsValid)
            {
                prodDatabaseEntities = new ProductDatabaseEntities();
                //sde.Products.Add(p);
                //Or
                prodDatabaseEntities.Entry(p).State = EntityState.Added;
                int x = prodDatabaseEntities.SaveChanges();
                if (x > 0)
                {
                    return RedirectToAction("Select");
                }
            }
            return View();
}

// GET: Edit
 [HttpGet]
public ActionResult Edit(int prodId)
{
            prodDatabaseEntities = new ProductDatabaseEntities();
            Product p = prodDatabaseEntities.Products.Single(m => m.ProductId == prodId);
            return View(p);
}

// POST: Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ProductName,ProductCode,ProductQty,ProductWeight,ProductDesc")] Product p)
{
            if (ModelState.IsValid)
            {
                prodDatabaseEntities = new ProductDatabaseEntities();

                UpdateModel(p);
                prodDatabaseEntities.Entry(p).State = EntityState.Modified;
                int x = prodDatabaseEntities.SaveChanges();
                if (x > 0)
                {
                    return RedirectToAction("Select ");
                }
            }
            return View();
}

// GET: Details
[HttpGet]
public ActionResult Details(int prodId)
{
            prodDatabaseEntities = new ProductDatabaseEntities();

            Product p = prodDatabaseEntities.Products.Single(m => m.ProductId == prodId);
            return View(p);
}

// GET: Delete
[HttpGet]
[ActionName("Delete")]
public ActionResult Delete_Get(int prodId)
{
            prodDatabaseEntities = new ProductDatabaseEntities();

            Product p = prodDatabaseEntities.Products.Single(m => m.ProductId == prodId);
            return View(p);
}

// POST: Delete
[HttpPost]
[ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult Delete_Post(int prodId)
{
            prodDatabaseEntities = new ProductDatabaseEntities();

            Product p = prodDatabaseEntities.Products.Single(m => m.ProductId == prodId);

            prodDatabaseEntities.Entry(p).State = EntityState.Deleted;
            int x = prodDatabaseEntities.SaveChanges();
            if (x > 0)
            {
                return RedirectToAction("Select ");
            }
            return View(p);
}

Note:-
Delete Operation, using the [ActionName("Delete")] attribute.  Because same Action Name with same signature not allowed.

Step 2:- To Add View of Action Method, Right-click inside the Select Action body => Click Add View => Click Add



Note:-
I chosen Templates: Empty (Without Model). Reason behind that everything builds with scrap.

Follow Step 2 for remaining Action Method.


Step 3:- Double-click Select.cshtml in Solution Explorer to open and decorate Select.cshtml view with following code

@model IEnumerable<MvcCRUDWithEntity.Models.Product>

@{
    ViewBag.Title = "Select";
}

<h2>Select</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table border="1" cellspacing="5" cellpadding="5">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.ProductName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ProductCode)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ProductQty)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ProductWeight)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ProductDesc)
        </th>
        <th>Action</th>
    </tr>
    @if (Model != null)
    {
        foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.ProductName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ProductCode)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ProductQty)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ProductWeight)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ProductDesc)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { prodId = item.ProductId }) |
                    @Html.ActionLink("Details", "Details", new { prodId = item.ProductId }) |
                    @Html.ActionLink("Delete", "Delete", new { prodId = item.ProductId })
                </td>
            </tr>
        }
    }
</table>

Step 4:- Double-click Create.cshtml in Solution Explorer to open and decorate Create.cshtml view with following code

@model MvcCRUDWithEntity.Models.Product

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <table border="1" cellspacing="5" cellpadding="5">
        <tr>
            <td>@Html.LabelFor(model => model.ProductName)</td>
            <td>
                @Html.EditorFor(model => model.ProductName)
                @Html.ValidationMessageFor(model => model.ProductName)
            </td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.ProductCode)</td>
            <td>
                @Html.EditorFor(model => model.ProductCode)
                @Html.ValidationMessageFor(model => model.ProductCode)
            </td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.ProductQty)</td>
            <td>
                @Html.EditorFor(model => model.ProductQty)
                @Html.ValidationMessageFor(model => model.ProductQty)
            </td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.ProductWeight)</td>
            <td>
                @Html.EditorFor(model => model.ProductWeight)
                @Html.ValidationMessageFor(model => model.ProductWeight)
            </td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.ProductDesc)</td>
            <td>
                @Html.EditorFor(model => model.ProductDesc)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Create" />
            </td>
        </tr>
    </table>
}

<div>
    @Html.ActionLink("Back to List", " Select")
</div>

Step 5:- Double-click Edit.cshtml in Solution Explorer to open and decorate Edit.cshtml view with following code

@model MvcCRUDWithEntity.Models.Product

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>
<h4>Product</h4>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.HiddenFor(model => model.ProductId)
    <table border="1" cellspacing="5" cellpadding="5">
        <tr>
            <td>@Html.LabelFor(model => model.ProductName)</td>
            <td>
                @Html.EditorFor(model => model.ProductName)
                @Html.ValidationMessageFor(model => model.ProductName)
            </td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.ProductCode)</td>
            <td>
                @Html.EditorFor(model => model.ProductCode)
                @Html.ValidationMessageFor(model => model.ProductCode)
            </td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.ProductQty)</td>
            <td>
                @Html.EditorFor(model => model.ProductQty)
                @Html.ValidationMessageFor(model => model.ProductQty)
            </td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.ProductWeight)</td>
            <td>
                @Html.EditorFor(model => model.ProductWeight)
                @Html.ValidationMessageFor(model => model.ProductWeight)
            </td>
        </tr>
        <tr>
            <td>@Html.LabelFor(model => model.ProductDesc)</td>
            <td>
                @Html.EditorFor(model => model.ProductDesc)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Save" />
            </td>
        </tr>
    </table>
}

<div>
    @Html.ActionLink("Back to List", " Select")
</div>

Step 6:- Double-click Details.cshtml in Solution Explorer to open and decorate Details.cshtml view with following code

@model MvcCRUDWithEntity.Models.Product

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<h4>Product</h4>
<table border="1" cellspacing="5" cellpadding="5">
    <tr>
        <td>
            @Html.DisplayNameFor(model => model.ProductName)
        </td>
        <td>
            @Html.DisplayFor(model => model.ProductName)
        </td>
    </tr>
    <tr>
        <td>
            @Html.DisplayNameFor(model => model.ProductCode)
        </td>
        <td>
            @Html.DisplayFor(model => model.ProductCode)
        </td>
    </tr>
    <tr>
        <td>
            @Html.DisplayNameFor(model => model.ProductQty)
        </td>
        <td>
            @Html.DisplayFor(model => model.ProductQty)
        </td>
    </tr>
    <tr>
        <td>
            @Html.DisplayNameFor(model => model.ProductWeight)
        </td>
        <td>
            @Html.DisplayFor(model => model.ProductWeight)
        </td>
    </tr>
    <tr>
        <td>
            @Html.DisplayNameFor(model => model.ProductDesc)
        </td>
        <td>
            @Html.DisplayFor(model => model.ProductDesc)
        </td>
    </tr>
</table>
<p>
    @Html.ActionLink("Edit", "Edit", new { prodId = Model.ProductId }) |
    @Html.ActionLink("Back to List", " Select")
</p>

Step 7:- Double-click Delete.cshtml in Solution Explorer to open and decorate Delete.cshtml view with following code

@model MvcCRUDWithEntity.Models.Product

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<h4>Product</h4>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <table border="1" cellspacing="5" cellpadding="5">
        <tr>
            <td>
                @Html.DisplayNameFor(model => model.ProductName)
            </td>
            <td>
                @Html.DisplayFor(model => model.ProductName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.DisplayNameFor(model => model.ProductCode)
            </td>
            <td>
                @Html.DisplayFor(model => model.ProductCode)
            </td>
        </tr>
        <tr>
            <td>
                @Html.DisplayNameFor(model => model.ProductQty)
            </td>
            <td>
                @Html.DisplayFor(model => model.ProductQty)
            </td>
        </tr>
        <tr>
            <td>
                @Html.DisplayNameFor(model => model.ProductWeight)
            </td>
            <td>
                @Html.DisplayFor(model => model.ProductWeight)
            </td>
        </tr>
        <tr>
            <td>
                @Html.DisplayNameFor(model => model.ProductDesc)
            </td>
            <td>
                @Html.DisplayFor(model => model.ProductDesc)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Delete" />
            </td>
        </tr>
    </table>
}
<div>
    @Html.ActionLink("Back to List", " Select")
</div>

All View Done

Before Running the project change RouteConfig.cs file route setting, under App_Start folder in Solution Explorer



To perform validation on Product required fields, do following changes in the Product.cs file.




Run Project


1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete