0

I'm using EF 6 code first to manage my DB. I have a task class as such

public class Task{
    public Guid Id { get; set; }
    public ICollection<Timeframe> Timeframes { get; set; }
}

and a Timeframe class that looks like

public class Timeframe{
    public Guid Id { get; set; }
    public ICollection<Task> Tasks { get; set; }
}

This created the correct many to many table structure. My application workflow is such that the task and the timeframe are both going to exist before the task/timeframe relationship is saved. I'm having trouble getting the relationships to persist once they are created. I understand that the relationships are not taken into account when you set an entity to EntityState.Modified and that you actually have to modify the collection in order to get the relationship to persist. I'm using the following code to update the task.Timeframes collection to attached Timeframes which I thought would work

public void SaveTask(Task task)
{
    entities.Tasks.Attach(task);
    var timeframes = new List<Timeframe>();
    foreach (var tf in task.Timeframes)
    {
        entities.Timeframes.Attach(tf);
        timeframes.Add(tf);
    }
    entities.Entry(task).State = EntityState.Modified;
    task.Timeframes.Clear();
    timeframes.ForEach(t =>
    {
        task.Timeframes.Add(t);
    });
    entities.ChangeTracker.DetectChanges();

    entities.SaveChanges();
}

but my relationship is still not being persisted. I looked for a RelationshipManager by which I could manually set the relationship to added, but I can't figure out how to get to it if it exists in EF6. What am I doing wrong that is keeping my relationships from persisting?

sonicblis
  • 2,926
  • 7
  • 30
  • 48

1 Answers1

0

With further research and this answer, I was able to add using System.Data.Entity.Infrastructure; and change my persistence code to

public void SaveTask(Task task)
{
    entities.Tasks.Attach(task);                
    var objectContext = ((IObjectContextAdapter)entities).ObjectContext;
    foreach (var tf in task.Timeframes)
    {
         entities.Timeframes.Attach(tf);
         objectContext.ObjectStateManager.ChangeRelationshipState(task, tf, t => t.Timeframes, EntityState.Added);
    }
}

and my relationships finally persisted. I didn't expect this to have to be managed quite this manually, but hopefully this will help someone else in the same situation.

Community
  • 1
  • 1
sonicblis
  • 2,926
  • 7
  • 30
  • 48