此例子是使用LINQ2Dapper封装,效率优于EntityFramwork,并且支持.NetFramework和.NetCore框架,只依赖于Dapper
需要先引用包Kogel.Dapper.Extension和Kogel.Dapper.Extension.MsSql(目前还支持Oracle),Nuget上可以下载安装。
Model实体类
using Kogel.Dapper.Extension.Attributes;
public class users
{
/// <summary>
/// 用户id(特性Identity标识该字段为主键)
/// </summary>
[Identity]
[Display(Name = "用户id")]
public int id { get; set; }
/// <summary>
/// code
/// </summary>
[StringLength(50)]
[Display(Name = "code")]
public string code { get; set; }
/// <summary>
/// 用户名称
/// </summary>
[StringLength(50)]
[Display(Name = "用户名称")]
public string name { get; set; }
/// <summary>
/// 创建方式(1自定义角色 2通用角色)
/// </summary>
[Display(Name = "创建方式(1自定义角色 2通用角色)")]
public int createWay { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[Display(Name = "创建时间")]
public DateTime createDate { get; set; }
/// <summary>
/// 创建人
/// </summary>
[StringLength(50)]
[Display(Name = "创建人")]
public string createUsers { get; set; }
/// <summary>
/// 角色id
/// </summary>
[Display(Name = "角色id")]
public int roleId { get; set; }
Dapper帮助类(可以自己实现)
public enum Providers
{
SqlClient,
OracleClient,
// ReSharper disable once InconsistentNaming
SQLite
}
public class Resource
{
/// <summary>
/// 项目资源路径
/// </summary>
public static string url { get; set; }
/// <summary>
/// 数据库连接字符串
/// </summary>
public static string connectionString { get; set; }
}
public class DapperHelper : IDbConnection, IDisposable
{
public IDbConnection Connection { get; }
public string ConnectionString { get => Resource.connectionString; set => Connection.ConnectionString = value; }
public int ConnectionTimeout => Connection.ConnectionTimeout;
public string Database => Connection.Database;
public ConnectionState State => Connection.State;
/// <summary>
/// Dapper帮助类创建
/// </summary>
/// <param name="providers">连接数据库对象</param>
public DapperHelper(Providers providers = Providers.SqlClient)
{
switch (providers)
{
case Providers.SqlClient:
Connection = new SqlConnection(ConnectionString);
break;
case Providers.OracleClient:
// Connection = new OracleConnection(connectionString);
break;
default:
throw new ArgumentOutOfRangeException(nameof(providers), providers, null);
}
}
public DapperHelper(string connectionString, Providers providers = Providers.SqlClient)
{
switch (providers)
{
case Providers.SqlClient:
Connection = new SqlConnection(connectionString);
break;
case Providers.OracleClient:
// Connection = new OracleConnection(connectionString);
break;
default:
throw new ArgumentOutOfRangeException(nameof(providers), providers, null);
}
}
/// <summary>
/// 对象释放
/// </summary>
public void Dispose()
{
Connection.Dispose();
}
#region 通用方法
public IDbTransaction BeginTransaction() => Connection.BeginTransaction();
public IDbTransaction BeginTransaction(System.Data.IsolationLevel il) => Connection.BeginTransaction(il);
public void ChangeDatabase(string databaseName) => Connection.ChangeDatabase(databaseName);
public void Close() => Connection.Close();
public IDbCommand CreateCommand() => Connection.CreateCommand();
/// <summary>
/// 执行sql(返回影响行数)
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public int Execute(string sql, object param = null, CommandType commandType = CommandType.Text) => Connection.Execute(sql, param, null, null, commandType);
/// <summary>
/// 执行sql(返回DataReader对象)
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public IDataReader ExecuteReader(string sql, object param = null) => Connection.ExecuteReader(sql, param);
/// <summary>
/// 执行sql(返回第一行第一列的执行结果)
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public object ExecuteScalar(string sql, object param = null, CommandType commandType = CommandType.Text) => Connection.ExecuteScalar(sql, param, null, null, commandType);
public SqlMapper.GridReader QueryMultiple(string sql, object param = null) => Connection.QueryMultiple(sql, param);
/// <summary>
/// 查询sql(返回一个匿名类型的集合)
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public IEnumerable<dynamic> Query(string sql, object param = null)
{
return Connection.Query(sql, param);
}
/// <summary>
/// 查询sql(返回一个匿名类型)
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public dynamic QueryFirst(string sql, object param = null) => Connection.QueryFirst(sql, param);
public dynamic QueryFirstOrDefault(string sql, object param = null) => Connection.QueryFirstOrDefault(sql, param);
public dynamic QuerySingle(string sql, object param = null) => Connection.QuerySingle(sql, param);
public dynamic QuerySingleOrDefaul(string sql, object param = null) => Connection.QuerySingleOrDefault(sql, param);
/// <summary>
/// 查询sql(返回一个对象的集合)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public IEnumerable<T> Query<T>(string sql, object param = null) => Connection.Query<T>(sql, param);
public T QueryFirst<T>(string sql, object param = null) => Connection.QueryFirst<T>(sql, param);
public T QueryFirstOrDefault<T>(string sql, object param = null) => Connection.QueryFirstOrDefault<T>(sql, param);
public T QuerySingle<T>(string sql, object param = null) => Connection.QuerySingle<T>(sql, param);
public T QuerySingleOrDefault<T>(string sql, object param = null) => Connection.QuerySingleOrDefault<T>(sql, param);
public void Open()
{
Connection.Open();
}
#endregion
}
使用实例
//Dapper扩展
using Kogel.Dapper.Extension.MsSql;
using Kogel.Dapper.Extension.MsSql.Extension;
using Kogel.Dapper.Extension.MsSql.Helper;
namespace Kogel.Framework.Test.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
using (var conn = new DapperHelper())
{
//模型类属性不能出现可空类型,例如int? project_Role也是实体类
var list = conn.QuerySet<users>().Where(x => x.name.Contains("Y")).ToList();
//查询
var users = conn.QuerySet<users>().Where(x => x.code != "1").Get();
ViewData["Message"] = "Hellow " + users.name;
//模糊查询
var users1 = conn.QuerySet<users>().Where(x => x.name.Contains("Y")).Get();
ViewData["Message1"] = "Hellow " + users1.name;
//修改
users1.name = Guid.NewGuid().ToString();
users1.createDate = DateTime.Now;
int result = conn.CommandSet<users>().Where(x => x.id == 4).Update(users1);
ViewData["Message2"] = result;
//修改查询
var users2 = conn.QuerySet<users>().Where(x => x.name.Contains("Y")).UpdateSelect(x => new users { name = "Y11" }).FirstOrDefault();
ViewData["Message3"] = "Hellow " + users2.name;
//新增
int result2 = conn.CommandSet<users>().Insert(new users() { code = Guid.NewGuid().ToString(), name = "test", createWay = 1, createDate = DateTime.Now, roleId = 2 });
ViewData["Message4"] = result2;
//删除
int result3 = conn.CommandSet<users>().Where(x => x.roleId == 0).Delete();
ViewData["Message5"] = result3;
//不连表查询返回dynamic
var list1 = conn.QuerySet<users>().Where(x => x.code != "1").ToList(true);
//连表查询返回dynamic
var list2 = conn.QuerySet<users>().Where(x => x.code != "1").Join<users, project_Role>(x => x.roleId, y => y.id).ToList(true);
//SQL连表查询
var users3 = conn.Query<users>(@"SELECT * FROM USERS
LEFT JOIN PROJECT_ROLE ON PROJECT_ROLE.ID=USERS.ROLEID").ToList();
//翻页查询
var list3 = conn.QuerySet<users>().OrderBy(x => x.createDate).PageList(1, 10);
//翻页连表查询返回dynamic
var list4 = conn.QuerySet<users>().Join<users, project_Role>(x => x.roleId, y => y.id).OrderBy(x => x.createDate).PageList(1, 10, true);
//动态化查询
var list5 = conn.QuerySet<users>().Where(new users() { id = 2, name = "Y11" }).Get();
//连表使用主表和副表条件翻页查询
var list6 = conn.QuerySet<users>().Join<users, project_Role>(x => x.roleId, y => y.id).Where(x => x.name == "adonis")
.Where<project_Role>(x => x.projectId == 2 && x.enabled == true).OrderBy(x => x.createDate).PageList(1, 10, true);
//In查询
var userss = conn.QuerySet<users>().Where(x => x.id.In("1,2,3")).ToList();
//var users = conn.QuerySet<users>().Where(x => x.id >= 2).ToList();
}
stopwatch.Stop(); // 停止监视
TimeSpan timeSpan = stopwatch.Elapsed; // 获取总时间
return View();
}
}
}
完整Demo可以去Github上下载:
https://github.com/a935368322/Kogel.Dapper.Test
如有问题也可以加QQ群讨论:
技术群 305678651
[LINQ2Dapper]最完整Dapper To Linq扩展
原文地址:https://www.cnblogs.com/kogel/p/10805696.html