【EFCore】UseInMemoryDatabaseではTransactionが使えない
EntityFrameworkCoreの2系ではTransactionが張れない場合があります。
対象ライブラリ: Microsoft.EntityFrameworkCore 2系
https://www.nuget.org/packages/Microsoft.EntityFrameworkCore/
概要
タイトル通りの内容です。
発端
ユニットテストを組んでいた時、以下のようなメッセージと共に例外を吐きました。
Outcome: Failed
Error Message:
System.InvalidOperationException :
Warning as error exception for warning 'Microsoft.EntityFrameworkCore.Database.Transaction.TransactionIgnoredWarning':
Transactions are not supported by the in-memory store.
See http://go.microsoft.com/fwlink/?LinkId=800142 To suppress this Exception use the DbContextOptionsBuilder.ConfigureWarnings API.
ConfigureWarnings can be used when overriding the DbContext.OnConfiguring method or using AddDbContext on the application service provider.
Stack Trace: {以下スタックトレースのため省略}
分析
分析も何もなかったです。
全てメッセージに書かれていました。
かつ、ググったらIssueが出てきました。
https://github.com/aspnet/EntityFrameworkCore/issues/2866
原因は以下のコード、
options.UseInMemoryDatabase()
「UseInMemoryDatabaseではTransactionが使えない」みたいです。(タイトル回収)
解決方法
ConfigureWarningsを使用して対象のExceptionが吐かれないように出来ます。
(Transactionは張られないようです。)
options
.UseInMemoryDatabase()
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))
まとめ
ロールバックに関するテストを行う場合は別途テスト用のデータベース環境を用意する必要があります。
ただ、それをテストする必要があるかは別問題。