3

I'm using EF Core (v1.1.3) and C#.

In my unit tests I create a sqlite in-memory database using the code-first db model, and then populate it with some test data. However when loading a list of entities from the dB, then related entities are getting populated, despite no '.Include' being used.

If I use the same model to create an actual on-disk database and the do the same load, then the related entities only get loaded if I use an .Include.

Is this a bug in the sqlite in-memory implementation (v1.1.0), or am I missing something?

I have already checked that there is nothing being tracked in the database, and obviously I can't dispose the context and renew it because of it being in-memory, and I'm limited to this version of EF & Sqlite currently, due to legacy reasons.

Obviously I'd prefer to have an in-memory option for unit tests rather than start creating on-disk tests, for the performance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
d sharpe
  • 189
  • 2
  • 12
  • _"...and obviously I can't dispose the context and renew it because of it being in-memory..."_ - why not? –  Sep 18 '19 at 23:53
  • Please post [mcve] how you are creating your context for _"...However when loading a list of entities from the dB, then related entities are getting populated, despite no '.Include' being used..."_ –  Sep 18 '19 at 23:54
  • @MickeyD. I cant dispose of the context, because as soon as you do, all content will be lost ! I – d sharpe Sep 19 '19 at 01:41
  • After googling and reading [this answer](https://stackoverflow.com/a/50634745/585968), EF Core did not introduce automatic Lazy Loading (which would have explained your issue) until [**EF Core 2.1**](https://learn.microsoft.com/en-us/ef/core/querying/related-data#lazy-loading). Considering you are using EFC v1.1x, you should only have _eager_ and _explcit_ at your disposal. Not sure what is causing the issue sadly –  Sep 19 '19 at 09:54
  • _"I `cant dispose` of the `context`, because as soon as you do, all content will be `lost` !"_ - [Incorrect](https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite). Perhaps you are thinking about the _connection_? Ensure you are using `DbContextOptionsBuilder` –  Sep 19 '19 at 10:00
  • Did you found solution? I have the exact same problem with EF Core 3.1 – zoran Feb 24 '20 at 21:54
  • I've seen the same thing in EF Core on .NET 5 – Ben Jun 08 '21 at 17:00

1 Answers1

1

I had exactly the same problem.

What you need to do is set the state of the entity that you have created for the test to Detatched. Then, when you try to read the entity again, EF will fetch it from DB.

Write this line after you create new entity:

dbContext.Entry(entity).State = EntityState.Detached;
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
Fares S
  • 11
  • 1