d sharpe
d sharpe

Reputation: 189

Stop related entities being loaded automatically in Sqlite in-memory dB using Entity Framework Core

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.

Upvotes: 3

Views: 620

Answers (1)

Fares S
Fares S

Reputation: 11

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;

Upvotes: 1

Related Questions