Database Reference
In-Depth Information
7-8. Inserting Entities Using a Database Context
Problem
You want to insert entities in your model to the database using a database context.
Solution
Suppose that you have a model like the one shown in Figure 7-9 .
Figure 7-9. A model with employees and their tasks
The model in Figure 7-9 represents employees and their tasks. You want to insert new employees and their tasks
into the underlying database. To insert an Employee, create a new instance of Employee and call the Add() method
available on the Employees entity set in the context. To add a Task for an employee, create a new instance of Task and
add it to the Tasks collection of the employee. You must also call Add() to add either the employee or the task to the
database context. To persist the changes to the database, call the SaveChanges() method.
The code in Listing 7-6 demonstrates using Add() to add new objects to the database context and persist them
to the database with SaveChanges() .
Listing 7-6. Inserting New Entities into the Database
using (var context = new EF6RecipesContext())
{
var employee1 = new Employee {EmployeeNumber = 629,
Name = "Robin Rosen", Salary = 106000M };
var employee2 = new Employee {EmployeeNumber = 147,
Name = "Bill Moore", Salary = 62500M };
var task1 = new Task { Description = "Report 3rd Qtr Accounting" };
var task2 = new Task { Description = "Forecast 4th Qtr Sales" };
var task3 = new Task { Description = "Prepare Sales Tax Report" };
// use Add() on the Employees entity set
context.Employees.Add(employee1);
// add two new tasks to employee1's tasks
employee1.Tasks.Add(task1);
employee1.Tasks.Add(task2);
 
Search WWH ::




Custom Search