Database Reference
In-Depth Information
// add a task to the employee and use
// Add() to add the task to the database context
employee2.Tasks.Add(task3);
context.Tasks.Add(task3);
// persist all of these to the database
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
foreach (var employee in context.Employees)
{
Console.WriteLine("Employee: {0}'s Tasks", employee.Name);
foreach (var task in employee.Tasks)
{
Console.WriteLine("\t{0}", task.Description);
}
}
}
Following is the output of the code in Listing 7-6:
Employee: Bill Moore's Tasks
Prepare Sales Tax Report
Employee: Robin Rosen's Tasks
Report 3rd Qtr Accounting
Forecast 4th Qtr Sales
How It Works
In Listing 7-6, we used the Add() method available on the Employees and Tasks entity sets to add entities to the
database context.
When you add an entity to the database context, Entity Framework creates a temporary entity key for the newly
added entity. Entity Framework uses this temporary key to uniquely identify the entity. This temporary key is replaced
by a real key after the object is persisted to the database. If saving two entities to the database results in both entities
being assigned the same entity key, Entity Framework will throw an exception. This can happen if the keys are
assigned the same value by the client or by some store-generating process.
For foreign key associations, you can assign the foreign key property of an entity the value of the entity key of a
related entity. Although temporary keys are involved, Entity Framework will fix up the keys and relationships correctly
when the entities are saved to the database.
You can also use the Attach() method to add an entity to a database context. This is a two-step process. First
call Attach() with the entity. This adds it to the database context, but the change tracker initially marks the entity as
Unchanged. Calling SaveChanges() at this point will not save the entity to the database. The second step is to pass the
entity into the database context's Entry() method to obtain a DbEntityEntry instance and set its State property to the
new state: EntityState.Added . Calling SaveChanges() at this point will save the new entity to the database.
 
Search WWH ::




Custom Search