Tuesday, December 4, 2012

Inserting 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 INSERT a record into the Employee table, which includes a Foreign Key column DepartmentID.




1. Create an Object of the ADO.Net Entity Data Model class
2. Create an Object of the Employee Class
3. Add the details to be inserted to the Employee Object
4. Add the Employee Object to the ADO.Net Entity Data Model
5. Commit changes to the Model

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

EmployeesEntities dbContext = new EmployeesEntities();
//
Employee objEmployee = new Employee();
objEmployee.Name = "Chris";
objEmployee.DOB = "11/11/1967";
objEmployee.DOJ = "05/01/2009";
objEmployee.Phone = "111-222-3333";
objEmployee.Email = "chris@abcsoftware.com";
objEmployee.Department = (from dep in dbContext.Department
                          where dep.Name == "Finance"
                          select dep).First();
objEmployee.Salery = 6000;
//
dbContext.AddToEmployee(objEmployee);
dbContext.SaveChanges();

6. Notice that we are referring to the Departments object to get the DepartmentID value for the Employee table.
 
7. Once we execute the code, a new record for Chris will get inserted into the Employee Table.

Related Post
Concepts
ADO.NET Entity Framework
ADO.NET Entity Framework Architecture
Entity Data Model
LINQ To SQL Vs ADO.Net Entity Framework


Programming
ADO.Net Entity Data Model Prerequisite
Creating your First ADO.Net Entity Data Model
Selecting Data using ADO.Net Entity Framework
Selecting Data by Joining Tables using ADO.Net Entity Framework
Inserting Data using ADO.Net Entity Framework
Inserting Data with Foreign Key Reference using ADO.Net Entity Framework
Updating Data using ADO.Net Entity Framework
Updating Data with Foreign Key Reference using ADO.Net Entity Framework
Deleting Data using ADO.Net Entity Framework

Search other Products:
Flipkart.com

No comments: