I have the Calendar object and create it as follows:
public class Program
{
public static void Main(string[] args)
{
var clienteDAO = new ClienteDAO();
var treinoDAO = new TreinoDAO();
var agendaDAO = new AgendaDAO();
var treino1 = treinoDAO.ObterTreino(1);
var treino2 = treinoDAO.ObterTreino(2);
var agenda = new Agenda();
agenda.Data = new DateTime(2017,12,11);
agenda.Horario = "14:00";
agenda.Observacoes = "";
agenda.Treinos.Add(treino1);
agenda.Treinos.Add(treino2);
agendaDAO.Cadastrar(agenda, 2);
}
}
When registering, the EF of the error saying that there are multiple contexts managed the same object (in this case, the training object). This is because I used another context to search for the training. So I try to 'undo' and add to the context again, but the problem persists:
public class AgendaDAO
{
private PJContext _db = new PJContext();
public void Cadastrar(Agenda agenda, int clienteId)
{
agenda.ClienteId = clienteId;
foreach (var treino in agenda.Treinos)
{
_db.Entry(treino).State = EntityState.Detached;
_db.Entry(treino).State = EntityState.Added;
}
_db.Set<Agenda>().Add(agenda);
_db.SaveChanges();
}
}
System.InvalidOperationException: 'An entity object can not be referenced by multiple instances of IEntityChangeTracker.'
When I do the "Detached" it does not do any good, because I think that only the other context that is observing it can do that. Is there any way to get it out of context?