Preventing tracking issues when using EF Core SqlLite in Unit Tests

ε祈祈猫儿з 提交于 2019-11-30 19:07:17

The issue is in the setup. You are using same dbcontext everywhere. Therefore while calling update, EF throws exception that entity with same key is being tracked already. The code works in production because with every request passed to controller DI generates a new instance of controller. Since controller also have DbContext in constructor, in same service scope, DI will generate new dbcontext instance too. Hence your Edit action always have a fresh dbcontext. If you are really testing out your controller then you should make sure that your controller is getting a fresh dbcontext rather than a context which was already used.

You should change GetInMemoryApplicationIdentityContext method to return DbContextOptions then during setup phase, store the options in a field. Whenever you need dbcontext (during saving entity or creating controller), new up DbContext using the options stored in the field. That would give you desired separation and allow you to test your controller as it would be configured in production.

trevorc

In your test 'Arrange' you have created a new DiaryEntry and not disposed of your DbContext. In the 'Act' portion of your test (which would be your controller action) you have created another instance of DbContext and then try and update the same DiaryEntry. Unless you manually turn of tracking (which I would not do) EF doesn't know which context should track the DiaryEntry. Hence the error.

Correct answer: If I had to guess the culprit appears to be 'model.ToDiaryEntryDataEntity()'. In your controller action you aren't getting the entity from the database. You are passing in all of the values of that entity but your extension method is creating a new instance of the same entity which is what is confusing EF. Your controller action 'worked' only because your newly created DiaryEntry was not in the DbContext. In your test it is. – trevorc 1 hour ago

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!