Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

.NET Core 1.0 Connecting SQL Server Database

$
0
0

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, but for simplicity and continuity of our work, we are going to use 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 anymore as of writing. But, we have all of the core features like Connection, Command, Paramter, DataReader and other related objects.

.NET Core Database Provider

A .NET Core application can connect to a database through Database Provider. Database providers are database connectivity implementation for specific technology and are 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.
publicclassBaseDataAccess { protectedstringConnectionString{get;set;} publicBaseDataAccess() { } publicBaseDataAccess(stringconnectionString) { this.ConnectionString=connectionString; } privateSqlConnectionGetConnection() { SqlConnectionconnection=newSqlConnection(this.ConnectionString); if(connection.State!=ConnectionState.Open) connection.Open(); returnconnection; } protectedDbCommandGetCommand(DbConnectionconnection,stringcommandText,CommandTypecommandType) { SqlCommandcommand=newSqlCommand(commandText,connectionasSqlConnection); command.CommandType=commandType; returncommand; } protectedSqlParameterGetParameter(stringparameter,objectvalue) { SqlParameterparameterObject=newSqlParameter(parameter,value!=null?value:DBNull.Value); parameterObject.Direction=ParameterDirection.Input; returnparameterObject; } protectedSqlParameterGetParameterOut(stringparameter,SqlDbTypetype,objectvalue=null,ParameterDirectionparameterDirection=ParameterDirection.InputOutput) { SqlParameterparameterObject=newSqlParameter(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; } returnparameterObject; } protectedintExecuteNonQuery(stringprocedureName,List<DbParameter>parameters,CommandTypecommandType=CommandType.StoredProcedure) { intreturnValue=-1; try { using(SqlConnectionconnection=this.GetConnection()) { DbCommandcmd=this.GetCommand(connection,procedureName,commandType); if(parameters!=null&&parameters.Count>0) { cmd.Parameters.AddRange(parameters.ToArray()); } returnValue=cmd.ExecuteNonQuery(); } } catch(Exceptionex) { //LogException("FailedtoExecuteNonQueryfor"+procedureName,ex,parameters); throw; } returnreturnValue; } protectedobjectExecuteScalar(stringprocedureName,List<SqlParameter>parameters) { objectreturnValue=null; try { using(DbConnectionconnection=this.GetConnection()) { DbCommandcmd=this.GetCommand(connection,procedureName,CommandType.StoredProcedure); if(parameters!=null&&parameters.Count>0) { cmd.Parameters.AddRange(parameters.ToArray()); } returnValue=cmd.ExecuteScalar(); } } catch(Exceptionex) { //LogException("FailedtoExecuteScalarfor"+procedureName,ex,parameters); throw; } returnreturnValue; } protectedDbDataReaderGetDataReader(stringprocedureName,List<DbParameter>parameters,CommandTypecommandType=CommandType.StoredProcedure) { DbDataReaderds; try { DbConnectionconnection=this.GetConnection(); { DbCommandcmd=this.GetCommand(connection,procedureName,commandType); if(parameters!=null&&parameters.Count>0) { cmd.Parameters.AddRange(parameters.ToArray()); } ds=cmd.ExecuteReader(CommandBehavior.CloseConnection); } } catch(Exceptionex) { //LogException("FailedtoGetDataReaderfor"+procedureName,ex,parameters); throw; } returnds; } }
.NET Core 1.0 Connecting SQL Server Database

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 facilitate to easily replace SQL Database Provider with any other Data Provider as per requirements. We have explicitly returned base classes DbConnection, DbCommand, DbParameter and DbDataReader instead of SqlConnection, SqlCommand, SqlParameter and SqlDataReader to abstract database connectivity from imp

Viewing all articles
Browse latest Browse all 3160

Latest Images

Trending Articles