Testing an Entity Framework database connection

前端 未结 6 1670
我在风中等你
我在风中等你 2020-12-08 04:34

I have an app that connects to a MYSQL database through the entity framework. It works 100% perfectly, but I would like to add a small piece of code that will test the conne

6条回答
  •  天涯浪人
    2020-12-08 04:58

    I used the answer from @Sandor and did an extension method to use with EntityFramework Core.

    Here's the code:

    using Microsoft.EntityFrameworkCore;
    using System.Data.Common;
    
    namespace TerminalInventory
    {
        public static class ExtensionMethods
        {
            public static bool TestConnection(this DbContext context)
            {
                DbConnection conn = context.Database.GetDbConnection();
    
                try
                {
                    conn.Open();   // Check the database connection
    
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }
    }
    

    Now you just have to call:

    if (!context.TestConnection())
    {
        logger.LogInformation("No database connection. Check the connection string in settings.json. {0}", configuration["connectionString"]);
    
        return;
    }
    

提交回复
热议问题