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?