This simple example I will show how to save/update/delete records in the table using Entity Framework 4.0.
If other programmers find it useful, I'll create video tutorial and another tutorial that shows how to use stored procedures with entity framework.
For this purpose I create simple table in my School database called Dpt that has only 2 columns - DepartmentID and DepartmentName. DepartmentId has Identity Specification set to yes.
Next I create new project and name it 2012 Web Entity 4.0 CRUD Test
Add new item and select WebForm.
To simplify, this form will be very basic, it will not have any label controls, only:
- 1 drop down list called deparmentList, ensure that AutoPostBack is set to true
- 1 text box called departmentName
- 1 button called saveChanges (Text property set to Save)
- 1 button called deleteRecord (Text property set to Delete)
Right click solution, add new item
Select Data under installed templates, then ADO.NET Entity Data Model.
Because my DPT table belongs to School database, I named this file SchoolModel.edmx.
Click Add button
Entity Data Model Wizard is displayed, ensure Generate from database is selected and click Next.
On next screen click New Connection button
Select server name, credentials, database name and click OK.
On wizard screen ensure that
- Yes, include the sensitive data in the connection string is selected
- Save entity connection settings in Web.Config is selected and has value set to SchoolEntities (DatabaseName + Entities)
Click Next
Because I want to make it really easy, for this example I selected only one table (Dpt) and didn't selected any views or stored procedures. There will be another tutorial dedicated to stored procedures with entity framework.
Ensure that
- Pluralize or singularize generated object names is selected.
- Include foreign key columns in the model is selected (we don't have any for this simple example anyway)
Name Model Namespase SchoolModel (DatabaseName + Model).
Click Finish
SchoolModel.edmx file is created and displayed.
Double click on the WebForm1 to implement Page Load method. On page load, if not post back, we will call loadDepartments function, that will insert all available departments into departmentList.
here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadDepartments();
}
}
private void loadDepartments()
{
using (SchoolEntities schoolContext = new SchoolEntities())
{
var departments = from d in schoolContext.Dpts
orderby d.DepartmentName
select new
{
Name = d.DepartmentName,
Id = d.DepartmentId
};
departmentList.DataTextField = "Name"; //Name = d.DepartmentName,
departmentList.DataValueField = "Id"; //Id = d.DepartmentId
departmentList.DataSource = departments; //var departments
departmentList.DataBind();
// add new record to the list that will display as first item.
// when this items is selected, program will be saving record,
// otherwize it will update it.
departmentList.Items.Insert(0, new ListItem("Create new department", ""));
}
}
You can run the program now, if you had some records in DPT table, departmentList will be populated with department names. If not, then you will have one option there: create a new department.
Double click on the departmentList to implement selected index changed method
If selected index changed, program will try to populate deparment name text box with correct name based on department id selected in departmentList.
protected void departmentList_SelectedIndexChanged(object sender, EventArgs e)
{
if (departmentList.SelectedValue == "")
{
// if Create new department is selected, then set department name text box to empty string.
departmentName.Text = "";
}
else
{
// if not then try to find corresponding name for selected id
// (again, this is very simplified example, both departmentList and departmentName display the same value
using(SchoolEntities schoolContext = new SchoolEntities()){
int id = Convert.ToInt32(departmentList.SelectedValue);
List<Dpt> depts = (from d in schoolContext.Dpts
where d.DepartmentId == id
select d).ToList();
if (depts.Count() > 0)
{
Dpt department = depts[0];
department.DepartmentId = Convert.ToInt32(departmentList.SelectedValue);
departmentName.Text = department.DepartmentName;
}
else
{
departmentName.Text = "";
}
}
}
}
Next, I will save or insert new record into database.
Double click Save button and copy/paste the following code
protected void saveChagnes_Click(object sender, EventArgs e)
{
using (SchoolEntities schoolContext = new SchoolEntities())
{
Dpt department = new Dpt();
department.DepartmentName = departmentName.Text;
if (departmentList.SelectedValue == "")
{
// new record, save
// department id will be created automatically
schoolContext.Dpts.AddObject(department);
}
else
{
// existing record, update
// first get department id
department.DepartmentId = Convert.ToInt32(departmentList.SelectedValue);
schoolContext.Dpts.Attach(department);
// notify entity that this record has been modified.
schoolContext.ObjectStateManager.ChangeObjectState(department, System.Data.EntityState.Modified);
}
// now save changes
schoolContext.SaveChanges();
// reload department list
loadDepartments();
// ensure that just saved or update department info is displayed.
departmentList.Items.FindByValue(department.DepartmentId.ToString()).Selected = true;
}
}
Last part - delete. Double click delete button and copy the following code
protected void deleteRecord_Click(object sender, EventArgs e)
{
if (departmentList.SelectedValue != "")
{
using (SchoolEntities schoolContext = new SchoolEntities())
{
Dpt department = new Dpt();
// get id of the department to be deleted.
department.DepartmentId = Convert.ToInt32(departmentList.SelectedValue);
schoolContext.Dpts.Attach(department);
// indicate it will be deleted
schoolContext.ObjectStateManager.ChangeObjectState(department, System.Data.EntityState.Deleted);
schoolContext.SaveChanges();
loadDepartments();
departmentName.Text = "";
}
}
}
Watch on youtube - part 1
Watch on youtube - part 2
what is Dpts as you have not used it whole program??
ReplyDeleteit is, in few places, for instance here
ReplyDeletev var departments = from d in schoolContext.Dpts