Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: Re-finding objects recently added to context

I am using the entity framework and I'm having a problem with "re-finding" objects I just created... basically it goes like this:

string theId = "someId";  private void Test() {   using(MyEntities entities = new MyEntities())   {     EntityObject o = new EntityObject();     o.Id = theId;     entities.AddToEntityObject(o);     CallSomeOtherMethod(entities);   } }  void CallSomeOtherMethod(MyEntities ents) {   EntityObject search = ents.EntityObject.FirstOrDefault(o => o.Id == theId);   if(search == null)    {     Console.WriteLine("wha happened???");   } } 

(no guarantee the code works btw - it's all from my head)

Why doesn't the query "find" the EntityObject that was just created?

If I call SaveChanges() after the AddToEntityObject it works (which doesn't surprise me) but why doesn't it pull from the cache properly?

I'm still green on this stuff so I'm hoping that there's some really easy thing that I'm just overlooking...

Thanks

like image 442
dovholuk Avatar asked Mar 31 '09 00:03

dovholuk


People also ask

How do you refresh entities?

In order to refresh the data entities, you click Data management workspace > Framework parameters > Entity settings > Refresh entity list in D365FO.

How does EF track changes?

EF Core change tracking works best when the same DbContext instance is used to both query for entities and update them by calling SaveChanges. This is because EF Core automatically tracks the state of queried entities and then detects any changes made to these entities when SaveChanges is called.

What is EntityState modified?

EntityState.Added : EntityState.Modified; context.SaveChanges(); } } Note that when you change the state to Modified all the properties of the entity will be marked as modified and all the property values will be sent to the database when SaveChanges is called.


1 Answers

The newly added object is in the local DataSource, since it's not persisted yet in the database,

so you may say:

EntityObject search = ents.EntityObject.FirstOrDefault(o => o.Id == theId) ??                       ents.EntityObject.Local.FirstOrDefault(o => o.Id == theId); 
like image 190
Rady Avatar answered Sep 20 '22 19:09

Rady