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?

EntityFrameworkCore でログを出力したい!

Posted at

こんにちは。エンジニアの藤原です。

最近は .NET Webアプリケーション開発でDBフレームワークである EntityFrameWorkCore(以下、EFCoreと記載)を使用していました。

実際にコーディングを進めていくと、EFCoreが動いたときにどのような動きをしたかログに出力して確認したいことが多々あるかと思います。
ログを確認できれば実際に発行されたクエリをみて様々な対処が可能になります。

当たり前ですが、EFCoreもデータベースにSQLを投げているので当然ログ出力が可能です。

ではどのようにログ出力をすれば良いのか。を今回は記事に残しておこうかと思います。

本記事は以下を満たしている方向けです。
・簡単なプログラミング経験
・VisualStudioの使用経験

ログ出力方法

ログ出力するために、今回はDbContextクラスを改造します!
まだ手を加える前ですが、下記のようなDbContextクラスがあるとしましょう。

namespace TestProject.Test
{
    internal class TestDbContext:DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new SqlConnectionStringBuilder();
            builder.DataSource = @"(localdb)\\MSSQLLocalDB";
            
            builder.InitialCatalog = "TestDB";
            builder.IntegratedSecurity = true;

            optionsBuilder.UseSqlServer(builder.ConnectionString);
        }
    }
}

ログ出力をしたい場合には使用するデータベースをオプション指定しているコードに手を加えます。
今回はVSの出力ウィンドウに表示したいので、「System.Diagnostics.Debug.WriteLine」を使用します。

namespace TestProject.Test
{
    internal class TestDbContext:DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new SqlConnectionStringBuilder();
            builder.DataSource = @"(localdb)\\MSSQLLocalDB";
            
            builder.InitialCatalog = "TestDB";
            builder.IntegratedSecurity = true;

            // 追加
            optionsBuilder.UseSqlServer(builder.ConnectionString)
                .LogTo(message => System.Diagnostics.Debug.WriteLine(message));
        }
    }
}

コンソールで動かしている場合には「Console.WriteLine」を使用してください。
実際に確認してみるとVS上の「出力」ウィンドウでEFCoreの挙動を確認できます。
image.png

最後に

いかがだったでしょうか。
わずかな手間でEFCoreの実際の動きを確認できますので、開発中や不具合調査などで使わない手はないと思います。

開発において便利なEFCoreですが、今回のように実際の挙動を確認することは開発に欠かせません。
ぜひ試してみてください。

以上、藤原でした。

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?