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".
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.
- public class BaseDataAccess
- {
- protected string ConnectionString { get; set; }
- public BaseDataAccess()
- {
- }
- public BaseDataAccess(string connectionString)
- {
- this.ConnectionString = connectionString;
- }
- private SqlConnection GetConnection()
- {
- SqlConnection connection = new SqlConnection(this.ConnectionString);
- if (connection.State != ConnectionState.Open)
- connection.Open();
- return connection;
- }
- protected DbCommand GetCommand(DbConnection connection, string commandText, CommandType commandType)
- {
- SqlCommand command = new SqlCommand(commandText, connection as SqlConnection);
- command.CommandType = commandType;
- return command;
- }
- protected SqlParameter GetParameter(string parameter, object value)
- {
- SqlParameter parameterObject = new SqlParameter(parameter, value != null ? value : DBNull.Value);
- parameterObject.Direction = ParameterDirection.Input;
- return parameterObject;
- }
- protected SqlParameter GetParameterOut(string parameter, SqlDbType type, object value = null, ParameterDirection parameterDirection = ParameterDirection.InputOutput)
- {
- SqlParameter parameterObject = new SqlParameter(parameter, type); ;
- if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar || type == SqlDbType.NText || type == SqlDbType.Text)
- {
- parameterObject.Size = -1;
- }
- parameterObject.Direction = parameterDirection;
- if (value != null)
- {
- parameterObject.Value = value;
- }
- else
- {
- parameterObject.Value = DBNull.Value;
- }
- return parameterObject;
- }
- protected int ExecuteNonQuery(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
- {
- int returnValue = -1;
- try
- {
- using (SqlConnection connection = this.GetConnection())
- {
- DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
- if (parameters != null && parameters.Count > 0)
- {
- cmd.Parameters.AddRange(parameters.ToArray());
- }
- returnValue = cmd.ExecuteNonQuery();
- }
- }
- catch (Exception ex)
- {
- //LogException("Failed to ExecuteNonQuery for " + procedureName, ex, parameters);
- throw;
- }
- return returnValue;
- }
- protected object ExecuteScalar(string procedureName, List<SqlParameter> parameters)
- {
- object returnValue = null;
- try
- {
- using (DbConnection connection = this.GetConnection())
- {
- DbCommand cmd = this.GetCommand(connection, procedureName, CommandType.StoredProcedure);
- if (parameters != null && parameters.Count > 0)
- {
- cmd.Parameters.AddRange(parameters.ToArray());
- }
- returnValue = cmd.ExecuteScalar();
- }
- }
- catch (Exception ex)
- {
- //LogException("Failed to ExecuteScalar for " + procedureName, ex, parameters);
- throw;
- }
- return returnValue;
- }
- protected DbDataReader GetDataReader(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
- {
- DbDataReader ds;
- try
- {
- DbConnection connection = this.GetConnection();
- {
- DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
- if (parameters != null && parameters.Count > 0)
- {
- cmd.Parameters.AddRange(parameters.ToArray());
- }
- ds = cmd.ExecuteReader(CommandBehavior.CloseConnection);
- }
- }
- catch (Exception ex)
- {
- //LogException("Failed to GetDataReader for " + procedureName, ex, parameters);
- throw;
- }
- return ds;
- }
- }


Faraz KhanPosted Mar 20, 2017, 5:19 AM
Great work. how can i implement transaction?
Ian JoshPosted Nov 9, 2016, 5:40 AM
This is my first task on .net core and i have a db task to do. I have referenced Microsoft.EntityFrameworkCore.SqlServer as discussed here. However i don't get SqlConnection or DBCommand or DBConnection class. Can you tell me what i am missing?