Entity Framework 6: Context Management Problem

0

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?

    
asked by anonymous 16.11.2017 / 12:51

1 answer

2

You need to make the connection to the bank. When you do not do this, your first query causes the Entity Framework to track that object (Using .AsNoTracking() help does not happen). Then when you tried to add it, you were redoing the track of that object, so it was twice, that can not happen.

The problem with IQueryable is that it builds an expression tree from the query in the database, as long as you do not call the .Execute() or do the conversion, it did not query the values.

You were doing the dispose (action of releasing the connection to the database) before IQueryable actually ran and fetched the result of the query, as soon as you try to return it, it will see that the connection to the database has been released and the error happens.

    
16.11.2017 / 14:02