您的位置:首页 > 编程语言 > ASP

Asp.Net Core 2.0 项目实战(4)ADO.NET操作数据库封装、 EF Core操作及实例

2018-05-31 19:10 1016 查看

Asp.Net Core 2.0 项目实战(1) NCMVC开源下载了

Asp.Net Core 2.0 项目实战(2)NCMVC一个基于Net Core2.0搭建的角色权限管理开发框架

Asp.Net Core 2.0 项目实战(3)NCMVC角色权限管理前端UI预览及下载

Asp.Net Core 2.0 项目实战(4)ADO.NET操作数据库封装、 EF Core操作及实例

Asp.Net Core 2.0 项目实战(5)Memcached踩坑,基于EnyimMemcachedCore整理MemcachedHelper帮助类。

Asp.Net Core 2.0 项目实战(6)Redis配置、封装帮助类RedisHelper及使用实例

Asp.Net Core 2.0 项目实战(7)MD5加密、AES&DES对称加解密

Asp.Net Core 2.0 项目实战(8)Core下缓存操作、序列化操作、JSON操作等Helper集合类

Asp.Net Core 2.0 项目实战(9) 日志记录,基于Nlog或Microsoft.Extensions.Logging的实现及调用实例

Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录

Asp.Net Core 2.0 项目实战(11) 基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级

本文目录
1. 摘要
2. Ado.Net数据库操作封装类
3. EF Core数据库操作
4. 总结

1.  摘要

  Asp.Net Core2.0下操作MSSQL数据库,这里介绍两种操作方式,一种是.NET Framework的ADO.NET《Ado.Net百科》,另一种就是Net Core2.0下的一种orm操作EF Core,由于本人习惯Ado.Net编程模式,EF Core涉猎不是很深,推荐网友连接,本文有不写的不到之处欢迎大家批评指正。

2.  Ado.Net数据库操作封装类

  2.1配置文件

    在appsettings.json添加相关配置,配置数据库连接字符串,配置与原来在web.config中基本一致,只是形式略有差异。

//数据库连接
"ConnectionStrings": {
"SqlDSN": "server=.;uid=sa;pwd=123456;database=NCMVC;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=false;"
}

using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using System.Data.SqlClient;
using System.Data;
using System;
using System.Collections;
using System.Reflection;

using NC.Common;
namespace NC.Core
{
public class DbHelper
{
public static ILogger Log = UtilLogger<DbHelper>.Log;//日志记录

#region --定义变量--
public string dsn;
//默认实例 : DbCommand.SqlDSN.CraeteSqlDataTable(sql, p);
public static DbHelper SqlDSN { get { return new DbHelper(); } }

#endregion

#region --构造函数--
/// <summary>
/// 构造函数
/// </summary>
public DbHelper()
{
//dsn = Encrypt.Dec(dsn);  //解密
//dsn = Configuration.GetConnectionString("SqlDSN");
dsn = UtilConf.GetConnectionString("SqlDSN");
}
/// <summary>
/// 多数据库
/// </summary>
/// <param name="strDSN"></param>
public DbHelper(string strDSN)
{
Log.LogInformation(strDSN);
//dsn = Configuration.GetConnectionString(strDSN);
dsn = UtilConf.GetConnectionString(strDSN);
}
#endregion

#region ** 打开/关闭链接 **
/// <summary>
/// 打开链接
/// </summary>
private void ConnOpen(ref SqlCommand comd)
{
if (comd.Connection.State == ConnectionState.Closed)
comd.Connection.Open();
}

/// <summary>
/// 关闭链接
/// </summary>
private void ConnClose(ref SqlCommand comd)
{
if (comd.Connection.State == ConnectionState.Open)
{
comd.Connection.Close();
}
comd.Dispose();
}
#endregion

#region ** 创建 SqlCommand 对象
/// <summary>
/// 生成comd对象
/// </summary>
public SqlCommand CreateComd(string spName)
{
try
{
SqlConnection conn = new SqlConnection(dsn);
SqlCommand comd = conn.CreateCommand();
comd.CommandText = spName;
comd.CommandType = CommandType.StoredProcedure;

return comd;
}
catch (System.Exception ex)
{
Log.LogError("DbCommand->CreateComd(sp) 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
public SqlCommand CreateComd(string spName, DbParameters p)
{
try
{
SqlCommand comd = CreateComd(spName);

int len = p.Length;
if (len > 0)
{
for (int i = 0; i < len; i++)
{
comd.Parameters.Add(p[i]);
}
}
return comd;
}
catch (System.Exception ex)
{
Log.LogError("DbCommand->CreateComd(sp) 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
public SqlCommand CreateSqlComd(string strSql)
{
try
{
SqlConnection conn = new SqlConnection(dsn);
SqlCommand comd = conn.CreateCommand();
comd.CommandText = strSql;
comd.CommandType = CommandType.Text;

return comd;
}
catch (System.Exception ex)
{
Log.LogError("DbCommand->CreateSqlComd(s) 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
public SqlCommand CreateSqlComd(string strSql, DbParameters p)
{
try
{
SqlCommand comd = CreateSqlComd(strSql);

int len = p.Length;
if (len > 0)
{
for (int i = 0; i < len; i++)
{
comd.Parameters.Add(p[i]);
}
}
return comd;
}
catch (System.Exception ex)
{
Log.LogError("DbCommand->CreateSqlcomd(s,p) 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
#endregion

#region ** 创建 SqlDataAdapter 对象
/// <summary>
/// 根据存储过程名,生成SqlDataAdapter对象
/// </summary>
public SqlDataAdapter CreateAdapter(string spName)
{
try
{
SqlConnection conn = new SqlConnection(dsn);
SqlDataAdapter comdAdapter = new SqlDataAdapter(spName, conn);
comdAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;

return comdAdapter;
}
catch (System.Exception ex)
{
Log.LogError("DbCommand->CreateAdapter(s) 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
/// <summary>
/// 根据存储过程名和参数,生成SqlDataAdapter对象
/// </summary>
public SqlDataAdapter CreateAdapter(string spName, DbParameters p)
{
try
{
SqlDataAdapter comdAdapter = CreateAdapter(spName);

int len = p.Length;
if (len > 0)
{
for (int i = 0; i < len; i++)
{
comdAdapter.SelectCommand.Parameters.Add(p[i]);
}
}

return comdAdapter;
}
catch (System.Exception ex)
{
Log.LogError("DbCommand->CreateAdapter(s, p) 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
/// <summary>
/// 根据SQL语句,生成DataAdapter对象
/// </summary>
public SqlDataAdapter CreateSqlAdapter(string strSql)
{
try
{
SqlConnection conn = new SqlConnection(dsn);
SqlDataAdapter apter = new SqlDataAdapter(strSql, conn);
apter.SelectCommand.CommandType = CommandType.Text;

return apter;
}
catch (System.Exception ex)
{
Log.LogError("DbCommand->CreateSqlAdapter(s) 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
/// <summary>
/// 根据SQL语句和参数,生成DataAdapter对象
/// </summary>
public SqlDataAdapter CreateSqlAdapter(string strSql, DbParameters p)
{
try
{
SqlDataAdapter apter = CreateSqlAdapter(strSql);

int len = p.Length;
if (len > 0)
{
for (int i = 0; i < len; i++)
{
apter.SelectCommand.Parameters.Add(p[i]);
}
}

return apter;
}
catch (System.Exception ex)
{
Log.LogError("DbCommand->CreateSqlAdapter(s,p) 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
#endregion

#region ** 创建 DataReader 对象
/// <summary>
/// 根据存储过程生成生SqlDataReader
/// </summary>
public SqlDataReader CreateDataReader(string spName)
{
SqlCommand comd = CreateComd(spName);
return GetDataReader(comd);
}
/// <summary>
/// 根据存储过程和参数生成SqlDataReader
/// </summary>
public SqlDataReader CreateDataReader(string spName, DbParameters p)
{
SqlCommand comd = CreateComd(spName, p);
return GetDataReader(comd);
}
/// <summary>
/// 根据SQL语句生成SqlDataReader
/// </summary>
public SqlDataReader CreateSqlDataReader(string strSql)
{
SqlCommand comd = CreateSqlComd(strSql);
return GetDataReader(comd);
}
/// <summary>
/// 根据SQL语句和参数生成SqlDataReader
/// </summary>
public SqlDataReader CreateSqlDataReader(string strSql, DbParameters p)
{
SqlCommand comd = CreateSqlComd(strSql, p);
return GetDataReader(comd);
}

#region - GetDataReader()
//获取DataReader
private SqlDataReader GetDataReader(SqlCommand comd)
{
try
{
ConnOpen(ref comd);
return comd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->GetDataReader() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
#endregion
#endregion

#region ** 创建 DataTable 对象
/// <summary>
/// 根据存储过程创建 DataTable
/// </summary>
public DataTable CreateDataTable(string spName)
{
SqlDataAdapter adapter = CreateAdapter(spName);
return GetDataTable(adapter);
}
/// <summary>
/// 根据存储过程和参数创建 DataTable
/// </summary>
public DataTable CreateDataTable(string spName, DbParameters p)
{
SqlDataAdapter adapter = CreateAdapter(spName, p);
return GetDataTable(adapter);
}
/// <summary>
/// 根据SQL语句,创建DataTable
/// </summary>
public DataTable CreateSqlDataTable(string strSql)
{
SqlDataAdapter adapter = CreateSqlAdapter(strSql);
return GetDataTable(adapter);
}
/// <summary>
/// 根据SQL语句和参数,创建DataTable
/// </summary>
public DataTable CreateSqlDataTable(string strSql, DbParameters p)
{
SqlDataAdapter adapter = CreateSqlAdapter(strSql, p);
return GetDataTable(adapter);
}

#region  - GetDataTable()
private DataTable GetDataTable(SqlDataAdapter adapter)
{
try
{
DataTable dt = new DataTable();
adapter.Fill(dt);

return dt;
}
catch (System.Exception ex)
{
Log.LogError("DbCommand->GetSqlDataTable() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
finally
{
if (adapter.SelectCommand.Connection.State == ConnectionState.Open)
{
adapter.SelectCommand.Connection.Close();
}
adapter.Dispose();
}
}
#endregion

#endregion

#region ** 创建 Scalar 对象
/// <summary>
/// 创建无参数的 Scalar 对象
/// </summary>
public object CreateScalar(string spName)
{
SqlCommand comd = CreateComd(spName);
return GetScalar(comd);
}
/// <summary>
/// 有参数的 Scalar 对象
/// </summary>
public object CreateScalar(string spName, DbParameters p)
{
SqlCommand comd = CreateComd(spName, p);
return GetScalar(comd);
}
/// <summary>
/// 根据SQL语句,创建Scalar对象
/// </summary>
public object CreateSqlScalar(string strSql)
{
SqlCommand comd = CreateSqlComd(strSql);
return GetScalar(comd);
}
/// <summary>
/// 根据SQL语句和参数,创建Scalar对象
/// </summary>
public object CreateSqlScalar(string strSql, DbParameters p)
{
SqlCommand comd = CreateSqlComd(strSql, p);
return GetScalar(comd);
}

#region - GetScalar()
private object GetScalar(SqlCommand comd)
{
try
{
ConnOpen(ref comd);
object o = comd.ExecuteScalar();
ConnClose(ref comd);

return o;
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->GetScalar() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
#endregion
#endregion

#region ** 执行数据库操作 - ToExecute() **
/// <summary>
/// 执行数据库操作
/// </summary>
private int ToExecute(SqlCommand comd)
{
try
{
ConnOpen(ref comd);
int iOk = comd.ExecuteNonQuery();
ConnClose(ref comd);
return iOk;
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->ToExecute() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}

private int ToExecuteInt(SqlCommand comd)
{
try
{
ConnOpen(ref comd);
int iOk = 0;
int.TryParse(comd.ExecuteScalar().ToString(), out iOk);
ConnClose(ref comd);
return iOk;
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->ToExecute() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
#endregion

#region ** 仅执行,不返回输出参数 **
/// <summary>
/// 根据存储过程执行
/// </summary>
public int Execute(string spName)
{
SqlCommand comd = CreateComd(spName);
return ToExecute(comd);
}
/// <summary>
/// 根据存储过程和参数执行
/// </summary>
public int Execute(string spName, DbParameters p)
{
SqlCommand comd = CreateComd(spName, p);
return ToExecute(comd);
}
/// <summary>
/// 执行sql语句
/// </summary>
public int ExecuteSql(string sql)
{
SqlCommand comd = CreateSqlComd(sql);
return ToExecute(comd);
}

/// <summary>
/// 执行带参数的SQL语句
/// </summary>
public int ExecuteSqlInt(string sql, DbParameters p)
{
SqlCommand comd = CreateSqlComd(sql, p);
return ToExecuteInt(comd);
}
public int ExecuteSql(string sql, DbParameters p)
{
SqlCommand comd = CreateSqlComd(sql, p);
return ToExecute(comd);
}

#endregion

#region ** 执行并返回输出参数 **
/// <summary>
/// 执行并返回输出参数
/// </summary>
public string ExecuteOut(string spName, DbParameters p, string outParamName)
{
SqlCommand comd = CreateComd(spName, p);
//comd.Parameters.Add(new SqlParameter(outParamName, SqlDbType.VarChar, 50));
//comd.Parameters[outParamName].Direction = ParameterDirection.Output;

try
{
ConnOpen(ref comd);
comd.ExecuteNonQuery();
object o = comd.Parameters[outParamName].Value;
ConnClose(ref comd);

return (o == null) ? "" : o.ToString();
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->ExecuteOut() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}

/// <summary>
/// 执行并返回输出参数:默认输出参数 @Result Varchar(50)
/// </summary>
public string ExecuteOut(string spName, DbParameters p)
{
SqlCommand comd = CreateComd(spName, p);
comd.Parameters.Add(new SqlParameter("@Result", SqlDbType.VarChar, 50));
comd.Parameters["@Result"].Direction = ParameterDirection.Output;

try
{
ConnOpen(ref comd);
comd.ExecuteNonQuery();
object o = comd.Parameters["@Result"].Value;
ConnClose(ref comd);

return (o == null) ? "" : o.ToString();
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->ExecuteOut() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
#endregion

#region ** 执行并返回输出参数 **
/// <summary>
/// 执行存储过程,并返回输出参数
/// </summary>
public string ExecuteReturn(string spName, DbParameters p, string retParam)
{
SqlCommand comd = CreateComd(spName, p);
comd.Parameters.Add(new SqlParameter(retParam, SqlDbType.VarChar, 50));
comd.Parameters[retParam].Direction = ParameterDirection.ReturnValue;

//comd.Parameters.Add(new SqlParameter("ReturnValue",SqlDbType.Int,4, ParameterDirection.ReturnValue, false, 0, 0,String.Empty, DataRowVersion.Default, null));

try
{
ConnOpen(ref comd);
comd.ExecuteNonQuery();
object o = comd.Parameters[retParam].Value;
ConnClose(ref comd);

return (o == null) ? "" : o.ToString();
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->ExecuteReturn() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
public string ExecuteReturn(string spName, DbParameters p)
{
SqlCommand comd = CreateComd(spName, p);
comd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.VarChar, 50));
comd.Parameters["ReturnValue"].Direction = ParameterDirection.ReturnValue;

//comd.Parameters.Add(new SqlParameter("ReturnValue",SqlDbType.Int,4, ParameterDirection.ReturnValue, false, 0, 0,String.Empty, DataRowVersion.Default, null));

try
{
ConnOpen(ref comd);
comd.ExecuteNonQuery();
object o = comd.Parameters["ReturnValue"].Value;
ConnClose(ref comd);

return (o == null) ? "" : o.ToString();
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->ExecuteReturn() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
/// <summary>
/// 执行Sql语句,并返回返回值
/// </summary>
public string ExecuteSqlReturn(string sql, DbParameters p, string retParam)
{
SqlCommand comd = CreateSqlComd(sql, p);
comd.Parameters.Add(new SqlParameter(retParam, SqlDbType.VarChar, 50));
comd.Parameters[retParam].Direction = ParameterDirection.ReturnValue;

//comd.Parameters.Add(new SqlParameter("ReturnValue",SqlDbType.Int,4, ParameterDirection.ReturnValue, false, 0, 0,String.Empty, DataRowVersion.Default, null));

try
{
ConnOpen(ref comd);
comd.ExecuteNonQuery();
object o = comd.Parameters[retParam].Value;
ConnClose(ref comd);

return (o == null) ? "" : o.ToString();
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->ExecuteReturn() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}
/// <summary>
/// 根据Sql语句执行
/// </summary>
public string ExecuteSqlReturn(string sql, DbParameters p)
{
SqlCommand comd = CreateSqlComd(sql, p);
comd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.VarChar, 50));
comd.Parameters["ReturnValue"].Direction = ParameterDirection.ReturnValue;

//comd.Parameters.Add(new SqlParameter("ReturnValue",SqlDbType.Int,4, ParameterDirection.ReturnValue, false, 0, 0,String.Empty, DataRowVersion.Default, null));

try
{
ConnOpen(ref comd);
comd.ExecuteNonQuery();
object o = comd.Parameters["ReturnValue"].Value;
ConnClose(ref comd);

return (o == null) ? "" : o.ToString();
}
catch (System.Exception ex)
{
ConnClose(ref comd);
Log.LogError("DbCommand->ExecuteReturn() 出错\r\n" + ex.Message);
throw new Exception(ex.Message);
}
}

#endregion

}
}
DbHelper内容太多,请点击查看详细

  2.4调用实例

    读取DataTable:

    DataTable dt = new dbhelper().CreateSqlDataTable("select * from news ");

    读取单个字段:

    Object o=new dbhelper().CreateSqlScalar(“select title from news”);

    添加/修改删除

    String sql=””;

    DbParameters p = new DbParameters();

              p.Add("@id", id);

    int iRes=new dbhelper().ExecuteSql(sql, p);

    调用实例在《Asp.Net Core 2.0 项目实战(11基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级》中也有用到,权限管理控制抽时间在完善一篇,等项目雏形出来了,开源出来配合代码再分享一下,Ado.Net封住调用实例到时一看便知。

 

3.  EF Core数据库操作

  目前我了解到的EF Core已经支持大部分主流数据库如:Microsoft SQL Server、

  SQLite、Postgres (Npgsql)、 SQL Server Compact Edition、InMemory (for testing purposes);mysql现在不清楚是否已经支持了。

  我用的是数据库生成model这种方式,也就是DB First。参考

  https://www.cnblogs.com/tianma3798/p/6835400.html,https://www.cnblogs.com/luwenlong/p/7804227.html

  注意Net Core下MVC没NetFreamWork 下MVC管理Model的图形界面,nf下数据里改个字段可以在vs上直接右键重新生成model,现在还不太清楚怎么处理,ef core操作方式与原来也略有不同,现在用ef core的时候感觉比较繁琐。另数据库新增,修改,删除字段后,ef core怎么能快捷操作,有知道的朋友请留言告知,大家共同学习。

4.  总结

  无论技术怎么发展,还是由底层一代一代迭代出来的,基础还是要打好,Net Core2.0下操作数据库,牵扯到的内容太多,很多内容描述不出来,请大家配合代码理解实际动手操作一下,这里只能按心中所想配合项目实例列出重点,以及很多朋友可能会碰到的坑点,这里也当是自己的学习记录,有疑问欢迎留言大家讨论。

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐