Tuesday, December 4, 2012

Updating Data with Foreign Key Reference using ADO.Net Entity Framework

In order to select data from a Model using the ADO.Net Entity Data Model, we should first create an ADO.Net Entity Data Model class, refer to the post Creating your First ADO.Net Entity Data Model to see on how to create an ADO.Net Entity Data Model, that maps to the physical database.

Once you have created the ADO.Net Entity Data Model class, we can proceed with querying the model to select data. In this post we shall see on how to use the ADO.Net Entity Data Model to UPDATE a record in the Employee table, which references the Department Table through the Foreign Key DepartmentID 


1. Create an Object of the ADO.Net Entity Data Model class
2. Get the Object of the Employee whose details needs to be Updated
3. Update the details in the Employee Object
4. Commit changes to the Model

Here is the code to UPDATE rows using the ADO.Net Entity Data Model

EmployeesEntities dbContext = new EmployeesEntities();
//
// Get the Existing details of the Employee
Employee objEmployee = (from emp in dbContext.Employee
                        where emp.Name == "Tom"
                        select emp).First();
//
// Update the Employee Details
objEmployee.Name = "Joseph";
objEmployee.DOB = "12/12/1962";
objEmployee.DOJ = "02/02/2002";
objEmployee.Phone = "222-222-2222";
objEmployee.Email = "joseph@abcsoftware.com";
objEmployee.Department = (from dep in dbContext.Department
                          where dep.Name == "Sales"
                          select dep).First();
objEmployee.Salery = 7500;
//
// Save the Employee Details

Search Flipkart Products:
Flipkart.com

No comments: