Entity Framework: Avoid Saving Related Data/Graph Data/Navigation Property with Entity

Standard

First solution – use the same context for loading department and saving employee:

using (var context = new YourContext())
{
    var employee = new Employee();
    context.Employees.AddObject(employee);
    employee.Department = context.Departments.Single(d => d.Id == departmentId);
    context.SaveChanges();
}

Second solution – connect entities to the context separately and after that make reference between entities:

var employee = new Employee();
var department = GetDepartmentFromSomewhere(departmentId);

using (var context = new YourContext())
{
    context.Employees.AddObject(employee);
    context.Departments.Attach(department);
    employee.Department = department;
    context.SaveChanges();
}

Third solution – correct state of the department manually so that context doesn’t insert it again:

var employee = new Employee();
employee.Department = GetDepartmentFromSomewhere(departmentId);
using (var context = new YourContext())
{
    context.Employees.AddObject(employee);
    context.ObjectStateManager.ChangeObjectState(employee.Department, 
                                                 EntityState.Unchanged);
    context.SaveChanges();
}

Fourth solution – change related entity to null:

var employee = new Employee();
using (var context = new YourContext())
{
    employee.Department = null;
    context.Employees.AddObject(employee);
    context.SaveChanges();
}

Reference

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s