Question

I have written test code as bellow:

Entities db = new Entities();

var place = new Place
                {
                    Id = Guid.NewGuid(),
                    Name = "test",
                    Address = "address"
                };

db.Places.Add(place);

var cachedPlace = db.Places.Where(x => x.Id == place.Id).FirstOrDefault(); \\ null

I expected dbset will return the added entity. But it gives me object only after changes were saved to the real DB.

Was it helpful?

Solution

If you want to access the unsaved query, then you use the Local property of the DbSet.

The reason it doesn't work the way you want is that it must also support autonumbered identities, and that will mean the ID is 0. If you insert multiple records, you would have multiple objects with the same 0 ID. EF won't know what the real ID is until after it's been saved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top