CRUD Operations Using Entity Framework in ASP.NET MVC


Introduction

In this article we will see how to perform CRUD (Select, Insert, Update and Delete) operations using ADO.NET Entity Framework in ASP.NET MVC. In Select Insert, Update And Delete With ASP.NET MVC we see how to perform CRUD operations using ADO.Net.

In Select Insert, Update And Delete With ASP.NET MVC we used the simple DataSet, DataTable, DataReader, DataAtapter, Command and Connection objects of ADO.Net which is not the prefered way to work with ASP.NET MVC. According to the MVC standard we must use the Entity model to work with ASP.NET MVC. In this article we will see how to use this entity model to create our MVC application and how easy it is to use.

Step 1

Create the database and create one table called Authors using the following script in your database.

Create Table Author

(

AuthorId Int Primary Key Identity(1,1),

Name Varchar(100),
Location Varchar(50)
)

Step 2

Now our database is ready; we can use our database table to perform CRUD operations on it. Next create a new project by selecting ASP.NET MVC3 Web Application.

Step 3

For this article we will use ADO.NET Entity Framework as a model for the application so create the model by right-clicking on the Models folder and selecting ADO.Net Entity Model from the dialog and select generate from database like below.

model1.gif

Next it will ask whether to generate a model from the database or an empty model so select Generate From Database as in below.

model2.gif

Next the wizard will ask for connection information so provide the connection information and the name to entities as in the following diagram.

model3.gif

Next the wizard will ask to select objects so select our Author table from the list and finish it.

Step 4

In steps above you see how easily our model is ready to work. Next we have to add the controller so add one controller in the Controllers folder with the name Home. In this home controller we have various actions to perform the CRUD operation. To display all the records the first time, write the following action in the home controller.

[HttpGet]
public ActionResult Index()
{
     
 
return View(_dboperations.Authors.ToList());
}

In the code above we return the view as a list of all Authors present in our table. Here _dboperations is the instance name created on the top which is the instance for our AuthorEntities of model. Next we can add our view very easily as well so right-click in the index action and add the view like below.

model4.gif

In above screen check the checkbox "Create Strongly Typed View and select our model(Author) from the dropdown below that we have one option Scaffolding select the List from the dropdown and click on add. Now see the Index.aspx page which is already designed we need not design on our own.

Step 5

Next we will create four more actions; one for creating a new record, the second for edit and update, a third for displaying the details of a specific author and a fourth for deleting the Author. So copy and paste the following actions in your controller.

        [HttpGet]

        public ActionResult Edit(int id)
        {

            //Select The Name And Location Of Given AuthorId
            var authortoedit = (from n in _dboperations.Authors where n.AuthorId == id select n).First();
            //Return The View To Edit

            return View(authortoedit);
        }
        [HttpPost]
        public ActionResult Edit(Author authortoedit)
        {

            //Get The Existing Values
            var existingdetails = (from n in _dboperations.Authors where 
            n.AuthorId == authortoedit.AuthorId select.First();
            if (!ModelState.IsValid)
            {//if fails
                return View(existingdetails);
            }
            else
            {
                //if validation sucess
                _dboperations.ApplyCurrentValues(existingdetails.EntityKey.EntitySetName, authortoedit;
                _dboperations.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        //Returns view to create new records
        [HttpGet]

        public ActionResult Create()
        {
            return View();
        }
        //gets the values from view and insert to database
        [HttpPost]
        public ActionResult Create([Bind(Exclude="AuthorId")]Author authortocreate)
        {
            if (!ModelState.IsValid)
            {
                //if validation fails
                return View();
            }
            else
            {
                //If validation
                _dboperations.AddToAuthors(authortocreate);
                _dboperations.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        //Shwo the details of author
        [HttpGet]
        public ActionResult Details(int id)
        {
            var authordetails = (from n in _dboperations.Authors where n.AuthorId == id select n).First();

            return View(authordetails);
        }

        //delete from author
        public ActionResult Delete(int id)

        {
            //get the authorid to delete the record
            var authortodelete = _dboperations.Authors.First(n => n.AuthorId == id);
            _dboperations.DeleteObject(authortodelete);
            _dboperations.SaveChanges();

            return RedirectToAction("Index");
        }    

Step 6

Add the view as explained in step3 by changing scaffolding option e.g. for edit select edit, for details select details as given in the following diagrams:

  1. Edit:

    model5.gif

  2. Create:

    model6.gif

  3. Details:

    model7.gif

Now all the contents are ready; run your application and perform the CRUD on Author using ADO.NET Entity Framework.

Conclusion

Using less effort and less code we can create effective applications using an Entity Model with ASP.Net MVC.


Similar Articles