Why can’t I query for an added object before Savechanges?

Asked

Viewed 64 times

2

I need to add several objects to the database and some objects need another specific object that I 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 can’t you get it?

What I need to do to consult before a SaveChanges?


Method Buscar:

public TEntidade Buscar(Expression<Func<TEntidade, bool>> criterios)
{
    return Entidades.Where(criterios).SingleOrDefault();
}
  • How is your method Buscar?

  • I’ll edit the question and add what’s in mine Buscar.

  • @bigown, I edited the question and Entidades is a Dbset of the entity.

2 answers

2

Well, in SubItem = repositorioSubItem.Buscar(e => e.Valor1 = 1); you are sending search in context for an item that is not there, since the SaveChanges() not yet 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 he is instantiated in memory.

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

  • I understood why I could not search the object, but still in the real scenario I have a list and a foreach. This specific subitem with the Valor1 no longer exists and would need what I had just inserted in the previous iteration.

2


Philip,

As Tiago Cesar said, you cannot perform a query to the database relying on the entities inserted in the context until you execute the Savechanges command, as these are 'marked' as Added but the Insert instruction has not yet been executed. This way, at any time you can give a 'Rollback' and discard all operations that were performed in the context, instead of executing a SaveChanges.

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

  public TEntidade BuscarLocal(Func<TEntidade,bool> criterios)
  {
      return Entidades.Local.Where(criterios).SingleOrDefault();
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.