Database Reference
In-Depth Information
Listing 8-7. Deleting a POCO Entity with a Complex Type
int id = 0;
using (var context = new EFRecipesEntities())
{
var emp = context.Employees.Where(e =>
e.Name.FirstName.StartsWith("Bill")).FirstOrDefault();
id = emp.EmployeeId;
}
using (var context = new EFRecipesEntities())
{
var empDelete = new Employee
{
EmployeeId = id,
};
context.Employees.Attach(empDelete);
context.Employees.Remove(empDelete);
context.SaveChanges();
}
In Listing 8-7, we first have to find the EmployeeId of Bill Jordan. Because we are trying to show how we would
delete Bill without first loading the entity into the context, we create a new context to illustrate deleting Bill given just
his EmployeeId. We need to create an instance of the Employee entity complete with the Name type. Because we
are deleting, it doesn't matter much what values we put in for FirstName and LastName. The key is that the Name
property is not null. We satisfy this requirement by assigning a new (dummy) instance of Name. We then Attach() the
entity and call Remove () and SaveChanges() . This deletes the entity.
8-5. Notifying Entity Framework About Object Changes
Problem
You are using POCO, and you want to have Entity Framework and the object state manager notified of changes to your
objects.
Solution
Let's say that you have a model like the one in Figure 8-6 .
 
Search WWH ::




Custom Search