Skip to main content

Extension methods for the DbConnection class.

using System.Data;
using System.Linq;

namespace Extensions
{
    public static class DbConnectionExtensions
    {
        /// <summary>
        /// Returns true if the database connection is in one of the states received.
        /// </summary>
        /// <param name="self">The connection.</param>
        /// <param name="states">The states.</param>
        /// <returns></returns>
        public static bool StateIsWithin(this IDbConnection self, params ConnectionState[] states)
        {
            return (self != null &&
                    (states != null && states.Length > 0) &&
                    (states.Where(x => (self.State & x) == x).Any()));
        }

        /// <summary>
        /// Returns true if the database connection is in the specified state.
        /// </summary>
        /// <param name="self">The connection.</param>
        /// <param name="state">The state.</param>
        /// <returns></returns>
        public static bool IsInState(this IDbConnection self, ConnectionState state)
        {
            return (self != null &&
                    (self.State & state) == state);
        }

        /// <summary>
        /// Open the Database connection if not already opened.
        /// </summary>
        /// <param name="self">The connection.</param>
        public static void OpenIfNot(this IDbConnection self)
        {
            if (!self.IsInState(ConnectionState.Open))
            {
                self.Open();
            }
        }
    }
}