Sunday, March 13, 2011

Insert, Update and Delete using Entity Framework in Asp.MVC

In this tutorial, I will walk through all the steps necessary to create a

simple CRUD process in Asp.net MVC using Entity Framework



We'll start from adding a new Item to the final view


Go to Add New Item menu


We'll add an ADO.NET Entity Dta Model located in the data tab



Since we are generating the Model from database, we'll select the first option

the second option is to create a new model without previous database set up.

It's a good option if you are starting a new project from scratch


Next step is choose the database to be used in the project, .Net will

generate automatically the connection string



Now, you have to select the objects that you want to use in your project.

For this example, we'll use only the person table


This is the result object




Now, returning to MVC, I've added the Controller, Model and Views for person

You'll see their content in the upcoming screenshots




In the controller we have 4 actions, Index, Edit (get), Edit (post) and Delete




The model

Here is where the Entity object takes action.

First you'll need an instance of the entity object.


We'll use linq to performance SELECT statements, for INSERT

EF provdes a method AddObject(EntityObject), for UPDATE

ApplyCurrentValues(EntityObject), but before you have to

set to which row to want to update the values, DELETE

is done by calling DeleteObject(EntityObject)

In order to apply the changes in the database you have

to call the function SaveChanges.




And the Views

Index Views




Edit






If you have set everything correctly, the views should like like

Index





Add New Person





Edit Person






Delete

By clicking on delete, a confirmation dialog pops up

it'll delete only when hit on Yes. It's very important

ask for confirmation processes that involve update or delete

information





View refreshed




8 comments:

  1. please you send project for me ?

    email : duonghonganhcdth0803@gmail.com

    thanks

    ReplyDelete
  2. I'm not find table.Addobject() ?

    ReplyDelete
  3. Can you please post this project to my mail id,

    sathishkumar.kotha@gmail.com

    Thanks in advance,
    Satish

    ReplyDelete
  4. here is a simple way only using entityframework

    http://www.reddyinfosoft.blogspot.in/2012/05/insert-update-and-detele-in-entity.html

    ReplyDelete
  5. Can you please send me the soure code of this example...
    my email id is : jariwala_amin@ymail.com
    Thanks

    ReplyDelete
    Replies
    1. Hi Amin, this was written long ago, let me find it.

      Delete
  6. Very good tutorial. The screenshots, in particular, make it easy to follow.

    I've been having problems trying to get edit working correctly.

    Would you be able to send me the code to born_ignorant@hotmail.com?

    Cheers,

    Dan

    ReplyDelete
  7. hi..please use RAZOR instead of .aspx page which may be useful for all

    ReplyDelete