Why can not I query for an object added before SaveChanges?

2

I need to add multiple objects to the database and some objects need another specific object that I've added earlier.

When I make a query to get the object, it comes null.

Example:

var subItem = new SubItem
{
  Valor1 = 1,
  Valor2 = "Qualquer coisa"
};
repositorioSubItem.Inserir(subItem);

var item = new Item
{
  Etc = "Oi",
  SubItem = repositorioSubItem.Buscar(e => e.Valor1 = 1); //Valor NULL aqui
};
repositorioItem.Inserir(item);

contexto.SaveChanges();

Why do not you get it?

What do I need to do to query before a SaveChanges ?

Method Buscar :

public TEntidade Buscar(Expression<Func<TEntidade, bool>> criterios)
{
    return Entidades.Where(criterios).SingleOrDefault();
}
    
asked by anonymous 25.09.2014 / 20:01

2 answers

2

Philip,

As Tiago Cesar reported, you can not query the database by counting the entities entered in the context while not executing the SaveChanges command, because they are 'marked' as Added but the insert statement has not yet been executed. This way, at any time you can rollback and discard all the operations that were performed in the context, instead of executing a SaveChanges .

You can search for entities that have Added status but have not yet been entered (through SaveChanges ) using the Local property of DbSet . Your code would look like this:

  public TEntidade BuscarLocal(Func<TEntidade,bool> criterios)
  {
      return Entidades.Local.Where(criterios).SingleOrDefault();
  }
    
25.09.2014 / 20:59
2

Well, in SubItem = repositorioSubItem.Buscar(e => e.Valor1 = 1); you're prompting in context for an item that is not there, since SaveChanges() has not yet been executed. This results in a query SQL that does not find data (since they have not yet been saved). In your case, nothing prevents you from consuming subItem since it is instantiated in memory.

This is because the Entity Framework encapsulates transactions in transactions. Calling SaveChanges() effectively triggers the INSERT or UPDATE required to persist the data.

    
25.09.2014 / 20:06