Search code examples
c#entity-framework-6entity

What Is the Correct Way to Update a List with Entity?


I am trying to determine the preferred method of saving changes to a list. I can add the list and save changes, but unless I first explicitly remove all the list items from the database, I cannot save the updated list as Entity attempts to add it regardless of existing items, resulting in a primary key violation.

List<Task> tasks = (The list of tasks I want to save);
MainJob job = db.Jobs.SingleOrDefault(j => j.jobId == jobId);
job.task = tasks;
db.SaveChanges();

My model looks like this

public class MainJob
{
    public int jobId { get; set; }
    [ForeignKey("jobId")]
    public List<Task> task { get; set; }
}
public class Task
{
    [Key, Column(Order = 1)]
    [JsonIgnore]
    [Required]
    public int contractId { get; set; }

    [Key, Column(Order = 2)]
    public int taskId { get; set; }
}

Solution

  • You need to tell EF of any Tasks which have been saved. You can usually do this by looking at the ID. e.g.

    List<Task> tasks = (The list of tasks I want to save);
    
    MainJob job = db.Jobs.SingleOrDefault(j => j.jobId == jobId);
    
    job.task = tasks;
    
    foreach (var task in tasks)
    {
        if(task.contractId != 0) // New task
        {
            db.Tasks.Attach(task);
            db.Entry(task).State = EntityState.Modified; // If modified
    
            // otherwise can set it to Unchanged
            // db.Entry(task).State = EntityState.Unchanged;
        }
    }
    
    db.SaveChanges();
    

    Ofcourse if any tasks were deleted, you need to attach them and mark them as EntityState.Deleted, otherwise anything that is already in the database, will stay there.

    Your other option is to delete everything for your job in the Task table.