2

I am having an issue understanding why when adding a new entity to a DbSet of ObjectContext, that entity is not found will looking it up again.

using (var db = new SmartrailDB())
        {
            var cart01 = db.Carts.SingleOrDefault(x => x.Number == 0);
            if (cart01 == null)
            {
                cart01 = new Cart { Number = 0 };
                db.Carts.Add(cart01);

            }
            var cart02 = db.Carts.SingleOrDefault(x => x.Number == 0); // Should find the cart I just added - right?
            Assert.IsNotNull(cart02); // Fails because cart02 does not exist in the db.Carts collection
        }

Is anyone able to tell me what I am doing wrong here?

Also late on a Friday here so brain half asleep now.

Michael Smit
  • 51
  • 1
  • 7
  • The DbSet class always queries the database, not the local store. For more details, see the answers to [this question](https://stackoverflow.com/questions/699648/entity-framework-re-finding-objects-recently-added-to-context). – Doug Jul 05 '19 at 21:13

1 Answers1

-1

You have to update your context before you try to access the entity. Just do:

db.SaveChanges(); right after db.Cart.Add(cart01);

bobek
  • 8,003
  • 8
  • 39
  • 75
  • I can't do that as the transaction is not complete. The created entity may be used by subsequent records that form part of the transaction which is why I have this need. For now I am looking in Context.Carts.Local first for new entities and then a normal query. Hate the double work though as it feels like a work around. – Michael Smit May 13 '13 at 20:34
  • What if you were updating 20 thousand rows. Would you save the all at once and kill your website for half an hour or save it after each entity changed. You should save it and then continue with whatever you were doing. – bobek May 13 '13 at 23:26
  • Not related to my question but anyway - I do understand how to handle that. Each transaction results in about 50 to 70 records across a few tables. – Michael Smit May 14 '13 at 06:08