0
votes

I'm having a problem with the Entity Framework (EF4.1 - CodeFirst)

It's basically duplicating child objects ...

The object model is a number of Tasks within a Job -> the Task has a TaskType and that TaskType has a number of Statuses ...

At first it was duplicating TaskTypes on a save

However, after I added this it stopped duplicating the TaskTypes ...

context.Entry(task.TaskType).State = EntityState.Unchanged;

So I tried this for the statuses ...

        //tried this but it errors
        foreach (var status in task.TaskType.Statuses)
        {
            context.Entry(status).State = EntityState.Unchanged;
        }
        ////

But it Errors with the following ...

"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."

Heres the code in full ... (with some of the get code trimmed down for readability)

    using(var context = new JobContext())
    {
        var job = //Get with Includes;
        job.Tasks.Add(task);

        context.Jobs.Attach(job);

        context.Entry(task.TaskType).State = EntityState.Unchanged;

        //tried this but it errors
        foreach (var status in task.TaskType.Statuses)
        {
            context.Entry(status).State = EntityState.Unchanged;
        }
        ////

        context.SaveChanges();
    }

Can anyone assist please?

1

1 Answers

1
votes
using(var context = new JobContext())
{
    var job = //Get with Includes;
    context.Jobs.Attach(job); 
    // can be omitted if "Get with Includes" happens in the same context

    context.TaskTypes.Attach(task.TaskType);
    // attaches TaskType and all Statuses -> State is Unchanged

    job.Tasks.Add(task);
    // A new task will be created after SaveChanges. If you don't want that
    // replace Attach(task.TaskType) above by Attach(task)

    context.SaveChanges();
}

You don't need to load with Include by the way for this. You can load without Include (and then create an empty collection job.Tasks = new List<Task>()).