.NET Core 1.0 Connecting SQL Server Database

Let's discuss how to connect to the databases. In this session, we will connect to SQL Server Database from .NET Core Class Library and we will use Microsoft SQL Server Database Provider named as "Microsoft.EntityFrameworkCore.SqlServer".

Although, these are simple steps and can be performed in any project, for simplicity and continuity of our work, we are going to use the project created in our discussion Getting Started With ASP.NET Core 1.0 MVC.

It is important to note that .NET Core does not have DataSet, DataTable, and related objects any more as of this writing. But, we have all of the core features like Connection, Command, Parameter, DataReader and other related objects.

.NET Core Database Provider

A .NET Core application can connect to a database through a Database Provider. Database providers are database connectivity implementation for specific technologies and are an extension of System.Data.Common package. At the moment, .NET Core provides the following Database providers,
  • Microsoft SQL Server
  • SQLite
  • PostgreSQL
  • Microsoft SQL Server Compact Edition
  • IBM Data Servers
  • InMemory
  • MySQL (Under Devlopment)
  • Oracle (Under Devlopment)

Please refer to MSDN for more details on Database Providers.

Create Data Access Project

  • Open existing Solution in Visual Studio 2015.
  • Now, add new Client Library .NET Core project in Solution.

    • Open Add New Project Screen through Solution Context Menu >> Add >> New Project Or File >> New >> Project.
    • Select Class Library (.NET Core) Template through Installed >> Templates >> Visual C# >> .NET Core.
    • Name project as “WebApplicationCore.NetCore.DataAccess”.
    • Set suitable location as “C:\ASP.NET Core\Welcome To .NET Core 1.0\ ASP.NET Core” (selected by default to solution root).
    • Click OK button.

  • It will create a new class library project.

  • Add Reference to Microsoft.EntityFrameworkCore.SqlServer, using one of following methods.

    • Open Package Manger Console through Tools >> NuGet Packet Manger >> Package Manger Console and run install command "Install-Package Microsoft.EntityFrameworkCore.SqlServer" for WebApplicationCore.NetCore.DataAccess project.

    • Open NuGet Manager through WebApplicationCore.NetCore.DataAccess Reference context menu >> References >> Manage NuGet Packages. in Browse tab search for "Microsoft.EntityFrameworkCore.SqlServer" and install.

  • Rename Class1 as BaseDataAccess and add the required implementation to connect to SQL Server Database.
    1. public class BaseDataAccess  
    2. {  
    3.    protected string ConnectionString { get; set; }  
    4.   
    5.    public BaseDataAccess()  
    6.    {  
    7.    }  
    8.   
    9.    public BaseDataAccess(string connectionString)  
    10.    {  
    11.        this.ConnectionString = connectionString;  
    12.    }  
    13.   
    14.    private SqlConnection GetConnection()  
    15.    {  
    16.        SqlConnection connection = new SqlConnection(this.ConnectionString);  
    17.        if (connection.State != ConnectionState.Open)  
    18.            connection.Open();  
    19.        return connection;  
    20.    }  
    21.   
    22.    protected DbCommand GetCommand(DbConnection connection, string commandText, CommandType commandType)  
    23.    {  
    24.        SqlCommand command = new SqlCommand(commandText, connection as SqlConnection);  
    25.        command.CommandType = commandType;  
    26.        return command;  
    27.    }  
    28.   
    29.    protected SqlParameter GetParameter(string parameter, object value)  
    30.    {  
    31.        SqlParameter parameterObject = new SqlParameter(parameter, value != null ? value : DBNull.Value);  
    32.        parameterObject.Direction = ParameterDirection.Input;  
    33.        return parameterObject;  
    34.    }  
    35.   
    36.    protected SqlParameter GetParameterOut(string parameter, SqlDbType type, object value = null, ParameterDirection parameterDirection = ParameterDirection.InputOutput)  
    37.    {  
    38.        SqlParameter parameterObject = new SqlParameter(parameter, type); ;  
    39.   
    40.        if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar || type == SqlDbType.NText || type == SqlDbType.Text)  
    41.        {  
    42.            parameterObject.Size = -1;  
    43.        }  
    44.   
    45.        parameterObject.Direction = parameterDirection;  
    46.   
    47.        if (value != null)  
    48.        {  
    49.            parameterObject.Value = value;  
    50.        }  
    51.        else  
    52.        {  
    53.            parameterObject.Value = DBNull.Value;  
    54.        }  
    55.   
    56.        return parameterObject;  
    57.    }  
    58.   
    59.    protected int ExecuteNonQuery(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)  
    60.    {  
    61.        int returnValue = -1;  
    62.   
    63.        try  
    64.        {  
    65.            using (SqlConnection connection = this.GetConnection())  
    66.            {  
    67.                DbCommand cmd = this.GetCommand(connection, procedureName, commandType);  
    68.   
    69.                if (parameters != null && parameters.Count > 0)  
    70.                {  
    71.                    cmd.Parameters.AddRange(parameters.ToArray());  
    72.                }  
    73.   
    74.                returnValue = cmd.ExecuteNonQuery();  
    75.            }  
    76.        }  
    77.        catch (Exception ex)  
    78.        {  
    79.            //LogException("Failed to ExecuteNonQuery for " + procedureName, ex, parameters);  
    80.            throw;  
    81.        }  
    82.   
    83.        return returnValue;  
    84.    }  
    85.   
    86.    protected object ExecuteScalar(string procedureName, List<SqlParameter> parameters)  
    87.    {  
    88.        object returnValue = null;  
    89.   
    90.        try  
    91.        {  
    92.            using (DbConnection connection = this.GetConnection())  
    93.            {  
    94.                DbCommand cmd = this.GetCommand(connection, procedureName, CommandType.StoredProcedure);  
    95.   
    96.                if (parameters != null && parameters.Count > 0)  
    97.                {  
    98.                    cmd.Parameters.AddRange(parameters.ToArray());  
    99.                }  
    100.   
    101.                returnValue = cmd.ExecuteScalar();  
    102.            }  
    103.        }  
    104.        catch (Exception ex)  
    105.        {  
    106.            //LogException("Failed to ExecuteScalar for " + procedureName, ex, parameters);  
    107.            throw;  
    108.        }  
    109.   
    110.        return returnValue;  
    111.    }  
    112.   
    113.    protected DbDataReader GetDataReader(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)  
    114.    {  
    115.        DbDataReader ds;  
    116.   
    117.        try  
    118.        {  
    119.            DbConnection connection = this.GetConnection();  
    120.            {  
    121.                DbCommand cmd = this.GetCommand(connection, procedureName, commandType);  
    122.                if (parameters != null && parameters.Count > 0)  
    123.                {  
    124.                    cmd.Parameters.AddRange(parameters.ToArray());  
    125.                }  
    126.   
    127.                ds = cmd.ExecuteReader(CommandBehavior.CloseConnection);  
    128.            }  
    129.        }  
    130.        catch (Exception ex)  
    131.        {  
    132.            //LogException("Failed to GetDataReader for " + procedureName, ex, parameters);  
    133.            throw;  
    134.        }  
    135.   
    136.        return ds;  
    137.    }  
    138. }  

code

BaseDataAccess

BaseDataAccess is a helper class which encapsulates all the implementation to connect and fetch the data, it not only helps us to maintain the database connectivity-related code separately, but will also help to easily replace SQL Database Provider with any other Data Provider as per our requirements. We have explicitly returned base classes DbConnection, DbCommand, DbParameter and DbDataReader instead of SqlConnection, SqlCommand, SqlParameter and SqlDataReader to abstract database connectivity from implementer. In this way, we have to just change the BaseDataAccess to target to some other database. We have the following Components in this class,

  • ConnectionString
  • GetConnection
  • GetCommand
  • GetParameter
  • GetParameterOut
  • ExecuteNonQuery
  • ExecuteScalar
  • GetDataReader

ConnectionString

ConnectionString holds the connection string. We can either initialize directly from configurations by code, or we can initialize it through parameterized constructor. We will initialize it with the following value,

"Server=SqlServerInstanceName;Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true".

GetConnection
GetConnection creates a new connection of SqlConnection type and returns it after opening.

GetCommand
GetCommand creates a new command of SqlCommand according to specified parameters.

GetParameter
GetParameter creates a new parameter of SqlParameter and initialize it with provided value.

GetParameterOut
GetParameterOut creates a new parameter of SqlParameter type with parameter direct set to Output type.

ExecuteNonQuery

ExecuteNonQuery initializes connection, command, and executes ExecuteNonQuery method of command object. Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data. For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. Please refer to MSDN for more details about SqlCommand.ExecuteNonQuery.

ExecuteScalar

ExecuteScalar initializes connection, command, and executes ExecuteScalar method of command object. Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. Please refer to MSDN for more details about SqlCommand.ExecuteScalar.

ExecuteReader

ExecuteReader initializes connection, command and executes ExecuteReader method of command object. Provides a way of reading a forward-only stream of rows from a SQL Server database. We have explicitly omitted using block for connection as we need to return DataReader with open connection state. Now question raises that how will we handle connection close open, for this we have created DataReader with "CommandBehavior.CloseConnection", which means, connection will be closed as related DataReader is closed. Please refer to MSDN for more details about SqlCommand.ExecuteReader and SqlDataReader.

Using BaseDataAccess

We may recommend using BaseDataAccess as base class of any other class, ideally your actual DataAccess component. If you think, you don't need full DataAccess layer, then you can make this concrete class by removing abstract keyword from declaration and also make its protected methods to public/internal as per your requirements.

  1. public class TestDataAccess : BaseDataAccess  
  2.  {  
  3.     public TestDataAccess(string connectionString) : base(connectionString)  
  4.     {  
  5.     }  
  6.   
  7.     public List<Test> GetTests()  
  8.     {  
  9.         List<Test> Tests = new List<Test>();  
  10.         Test TestItem = null;  
  11.   
  12.         List<DbParameter> parameterList = new List<DbParameter>();  
  13.               
  14.         using (DbDataReader dataReader = base.ExecuteReader("Test_GetAll", parameterList, CommandType.StoredProcedure))  
  15.         {  
  16.             if (dataReader != null && dataReader.HasRows)  
  17.             {  
  18.                 while (dataReader.Read())  
  19.                 {  
  20.                     TestItem = new Test();  
  21.                     TestItem.TestId = (int)dataReader["TestId"];  
  22.                     TestItem.Name = (string)dataReader["Name"];  
  23.   
  24.                     Tests.Add(TestItem);  
  25.                 }  
  26.             }  
  27.         }  
  28.         return Tests;  
  29.     }  
  30.   
  31.     public Test CreateTest(Test Test)  
  32.     {  
  33.         List<DbParameter> parameterList = new List<DbParameter>();  
  34.   
  35.         DbParameter TestIdParamter = base.GetParameterOut("TestId", SqlDbType.Int, Test.TestId);  
  36.         parameterList.Add(TestIdParamter);  
  37.         parameterList.Add(base.GetParameter("Name", Test.Name));  
  38.   
  39.         base.ExecuteNonQuery("Test_Create", parameterList, CommandType.StoredProcedure);  
  40.   
  41.         Test.TestId = (int)TestIdParamter.Value;  
  42.   
  43.         return Test;  
  44.     }  
  45.  }  
  46.   
  47.   public class Test    
  48.   {    
  49.     public object TestId { get; internal set; }    
  50.     public object Name { get; internal set; }    
  51.   }    

Up Next
    Ebook Download
    View all
    Learn
    View all