0

If I do something like this

DBcontext.MyTable.Where(x => x.SomeGuid.ToString() == "00000000-0000-0000-0000-1234000001234");

Then that loads the entity which isn't what I want. I want to know, what entities have already been loaded

NB I want a list of ALL entities that have been loaded, not just a specific one.

The linked question in the comment answers the second part of this question so I've now removed that

tony
  • 2,178
  • 2
  • 23
  • 40
  • Possible duplicate of [Either get local entity or attach a new one](https://stackoverflow.com/questions/50748522/either-get-local-entity-or-attach-a-new-one) – Gert Arnold Nov 01 '19 at 08:14
  • Why do you want that in the first place? DbContext is a transient object, you *know* what objects were loaded because you loaded them in the same method you put the `using(var context=new MyContext())` clause. Even in an MVC controller, the objects were loaded in the same action – Panagiotis Kanavos Nov 01 '19 at 08:42
  • Purely for debugging – tony Nov 01 '19 at 08:49
  • Are you debugging EF Core itself? That's the only reason to want to check what is already loaded. If you need to, you can checn DbContext.ChangeTracker and use [ChangeTracker.Entries()](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.changetracking.changetracker.entries?view=efcore-3.0#Microsoft_EntityFrameworkCore_ChangeTracking_ChangeTracker_Entries) to get a list of tracking entries. – Panagiotis Kanavos Nov 01 '19 at 09:09
  • If you *really-really* want to you can check [DbContext.IDbContextDependencies.StateManager](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.microsoft-entityframeworkcore-internal-idbcontextdependencies-statemanager?view=efcore-3.0) which itself is [an internal class](https://github.com/aspnet/EntityFrameworkCore/blob/24b9aa1d2e14fe2e737255ede9b2a7a623fcf2af/src/EFCore/ChangeTracking/Internal/StateManager.cs) using , that uses another internal class etc. This is resolved through DI and EF Core tests register their own fake state managers – Panagiotis Kanavos Nov 01 '19 at 09:10
  • ChangeTracker.Entries() worked great thanks. One example of why we wanted to do this. We had a repo that was added with AddTransient, DBcontext.Attach said that the object was already loaded but we couldn't see anywhere where it could have been loaded. It turned out that this was a merge error and the same repo had been added a second time with AddScoped, which isn't an error – tony Nov 01 '19 at 09:51
  • AddTransient means the DbContext *won't* be disposed automatically. Every time you request one, the DI will create a new one. That's an important problem itself. – Panagiotis Kanavos Nov 01 '19 at 10:00

1 Answers1

1

To save someone hunting through the comments

MyClass a = (from x in DBcontext.ChangeTracker.Entries() where x.Entity is MyClass && ((MyClass)x.Entity).TheGuid == theGuid select (MyClass)x.Entity).FirstOrDefault();
tony
  • 2,178
  • 2
  • 23
  • 40