0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【EFCore2系】UseInMemoryDatabaseではTransactionが使えない

Last updated at Posted at 2018-12-12

【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))

まとめ

ロールバックに関するテストを行う場合は別途テスト用のデータベース環境を用意する必要があります。
ただ、それをテストする必要があるかは別問題。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?