3

I am using Entity Framework with self-tracking POCO objects. How do I know whether an object has been loaded in the DBContext or not, without making a query... what I want to know is: The object is loaded in memory or not?

All my objects have public virtual int Id {get;set;} representing the key.

Thanks!

Miguel Angelo
  • 23,796
  • 16
  • 59
  • 82
  • You said self-tracking POCO, marked your question with EF-4 and after that used `DbContext`. That makes your question quite ambiguous. So what are you using? – Ladislav Mrnka Aug 02 '11 at 19:37
  • I use objects that don't inherit from anything, this is POCO... isn't it? They are made so that self-tracking is possible, using all virtual properties, so that Proxies can be created... and my context is inherited from DbContext, in wich I have DbSet's to make queries and get objects from DB. Did I use the wrong terminology? May be I confused some concepts! – Miguel Angelo Aug 02 '11 at 20:11
  • Ok. You are using EF-4.1 and those entities are not self tracking. They only support dynamic change tracking. There is a big difference to [self-tracking](http://stackoverflow.com/questions/5091974/what-is-the-purpose-of-self-tracking-entities/5092097#5092097). – Ladislav Mrnka Aug 02 '11 at 20:43
  • If I create an object with db.Set().Create() (db is an instance of DbContext inherited class), and then change it, are you saying that it won't track changes by itself? Could you point some good reference on this *dynamic change tracking* please? Thanks! – Miguel Angelo Aug 02 '11 at 21:33
  • No it will not track changes itself. The dynamic proxy will tell the context that there was a change and context will track it. If the context is disposed tracking doesn't work but self-tracking entity is able to track changes even if the context doesn't exist. – Ladislav Mrnka Aug 02 '11 at 21:54

1 Answers1

4

To check if entity is tracked by your context you can use something like this:

bool tracked = context.ChangeTracker
                      .Entries<YourEntityType>()
                      .Any(e => e.Entity.Id == yourId);
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Could you please quickly explain how checking if the entity is'tracked' is different from checking if the entity is 'loaded'? I mean logically from EF point of view? Thanks. – NoChance May 29 '12 at 15:44