[LINQ2Dapper]最完整Dapper To Linq框架(一)---基础查询

此框架是Dapper的扩展,效率优于EntityFramwork,并且支持.NetFramework和.NetCore框架

支持.net framework4.5.1,.net core2.0及以上,更低版本适配如.netFramework4.0及以下请加群下载

支持Mssql,Oracle,Mysql等数据库

     应用层需要引用包Kogel.Dapper.Extension.MsSql(如果数据库是Oracle则引用Kogel.Dapper.Extension.Oracle),Nuget上可以下载安装。

或者使用Nuget命令添加包

Install-Package Kogel.Dapper.Extension.MsSql

 

 

(一)Model实体类 

 实体类层需要安装Kogel.Dapper.Extension表名字段特性。[更多特性详情请点击]

using Kogel.Dapper.Extension.Attributes;

 public class users
    {
        /// <summary>
        /// 用户id(特性Identity标识该字段为主键)
        /// </summary>    
        [Identity]
        public int id { get; set; }

        /// <summary>
        /// code
        /// </summary>    
        public string code { get; set; }

        /// <summary>
        /// 用户名称
        /// </summary>    
        public string name { get; set; }

        /// <summary>
        /// 创建方式(1自定义角色 2通用角色)
        /// </summary>    
        public int createWay { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>    
        public DateTime createDate { get; set; }

        /// <summary>
        /// 创建人
        /// </summary>    
        public string createUsers { get; set; }

        /// <summary>
        /// 角色id
        /// </summary>    
        public int roleId { get; set; }
}

 

(二)使用实例

首先添加命名空间

using Kogel.Dapper.Extension.MsSql;

可以通过数据库连接对象点出扩展方法,例如

var conn = new SqlConnection("数据库连接字符串");

 

使用完记得释放连接对象,可以通过using或者 conn.Dispose();


查询

var users = conn.QuerySet<users>().Where(x => x.code != "1").Get();

 

模糊查询

var users1 = conn.QuerySet<users>().Where(x => x.name.Contains("Y")).Get();

 

查询一个数组条件

int[] array = new int[] { 1, 2, 3 };
//使用In
var comment = conn.QuerySet<Comment>().Where(x => x.Id.In(array)).ToList();
//或者使用Contains
var comment = conn.QuerySet<Comment>().Where(x => array.Contains(x.Id)).ToList();

 

使用sql查询

DynamicParameters param = new DynamicParameters();
				param.Add("Id", 1);
var comment = conn.QuerySet<Comment>().Where("Id=@Id", param)
					.ToList();

 

范围查找 

var comment = conn.QuerySet<Comment>().Where(x => x.Id.Between(1, 10)).ToList();

  

修改

var users=new users();          
users.name = Guid.NewGuid().ToString();
users.createDate = DateTime.Now;
int result = conn.CommandSet<users>().Where(x => x.id == 4).Update(users);
 

自定义修改(修改指定字段)

int result = conn.CommandSet<Comment>()
                    .Where(x => x.Content == "test")
                    .Update(x => new Comment
                    {
                        Content = "test1"
                    });

 

新增  

int result = conn.CommandSet<users>()
                 .Insert(new users() { 
                       code = Guid.NewGuid().ToString(), 
                       name = "test", createWay = 1, 
                       createDate = DateTime.Now, 
                       roleId = 2 
                 }); 

 

 新增返回自增Id

int result = conn.CommandSet<users>()
                 .InsertIdentity(new users() { 
                       code = Guid.NewGuid().ToString(), 
                       name = "test", createWay = 1, 
                       createDate = DateTime.Now, 
                       roleId = 2 
                 });

  

删除

int result = conn.CommandSet<users>()
              .Where(x => x.roleId == 2 && x.name == users2.name)
              .Delete();

 

如果想使用事务

using (var conn = new SqlConnection(mysqlConnection))
{
                //必须先打开数据库
                conn.Open();
                //创建事务对象
                var transaction = conn.BeginTransaction();
                //使用事务对象做修改
                var result = conn.CommandSet<Comment>(transaction)
                    .Where(x => x.Id.Equals(1))
                    .Update(x => new Comment()
                    {
                        Content = "test"
                    });
                //提交事务,回滚使用  transaction.Rollback();
                transaction.Commit();
}

  

连表查询

Join<主表,副表>(主表关联字段,副表关联字段)

var list = conn.QuerySet<users>()
           .Where(x => x.code != "1")
           .Join<users, project_Role>(x => x.roleId, y => y.id)
           .ToList();

  

任意条件连表

var list = conn.QuerySet<users>()
           .Where(x => x.code != "1")
           .Join<users, project_Role>((x,y)=>x.roleId==y.id)
           .ToList();

  

还可以设置连表的方式(默认是Left Join)

var list = conn.QuerySet<users>()
           .Where(x => x.code != "1")
           .Join<users, project_Role>((x,y)=>x.roleId==y.id, JoinMode.LEFT)
           .ToList();

  

连表查询可以渲染成指定实体类,例如动态类型(dynamic)

var list = conn.QuerySet<users>()
           .Where(x => x.code != "1")
           .Join<users, project_Role>(x => x.roleId, y => y.id)
           .ToList<dynamic>();

 

 

翻页查询

//翻页查询第一页,10条数据
var list = conn.QuerySet<users>()
           .OrderBy(x => x.createDate)
           .PageList(1, 10);

//翻页连表查询返回dynamic
var list1 = conn.QuerySet<users>()
            .Join<users, project_Role>(x => x.roleId, y => y.id)
            .OrderBy(x => x.createDate)
            .PageList<dynamic>(1, 10);

 

多表任意联查         

 var users = conn.QuerySet<users>()
                        .Join<users, project_Role>((a, b) => a.roleId == b.id)
                        .Where<users, project_Role>((a, b) => a.id == 3 && b.id == 3)
                        .Get<dynamic>();

 

3.14版本后Where函数和匿名返回类型支持比较复杂的函数判断

例如

var comment1 = conn.QuerySet<Comment>()
                    .Join<Comment, News>((a, b) => a.ArticleId == b.Id)
                    .Where(x => x.Id.Between(80, 100)
                    && x.SubTime.AddDays(-10) < DateTime.Now && x.Id > 10
                    && x.Id > new QuerySet<News>(conn, new MySqlProvider()).Where(y => y.Id < 3 && x.Id<y.Id).Sum<News>(y => y.Id)
                    )
                    .From<Comment, News>()
                    .OrderBy<News>(x => x.Id)
                    .PageList(1, 1, (a, b) => new
                    {
                        test = new List<int>() { 3, 3, 1 }.FirstOrDefault(y => y == 1),
                        aaa = "6666" + "777",
                        Content = a.Content + "'test'" + b.Headlines + a.IdentityId,
                        bbb = conn.QuerySet<Comment>()
                                .Where(y => y.ArticleId == b.Id && y.Content.Contains("test")).Sum<Comment>(x => x.Id),
                        ccc = a.IdentityId,
                        ddd = Function.ConcatSql<int>("(select count(1) from Comment)"),
                        a.Id
                    });  

 

需要读取数据库的支持Sum和Count函数

不需要读取数据库的函数都支持,例如

 test = new List<int>() { 3, 3, 1 }.FirstOrDefault(y => y == 1)

  

批量新增

int result = conn.CommandSet<Comment>().Insert(commentList);  

以上操作都支持异步

 

3.1.8版本支持自定义导航查询

	var ContentList = conn.QuerySet<Comment>()
					 .ToList(x => new CommentDto()
					 {
						 Id = x.Id,
						 ArticleIds = x.ArticleId,
						 count = conn.QuerySet<News>().Where(y => y.Id == x.ArticleId).Count(),
						 NewsList = new QuerySet<News>().Where(y => y.Id == x.ArticleId).ToList(y => new NewsDto()
						 {
							 Id = y.Id,
							 Contents = y.Content
						 }).ToList()
					 });

(子属性返回暂时不支持匿名类)

(Dto类需要继承 IBaseEntity

 

(三)扩展的一些函数处理

Kogel.Dapper支持一些基础的sql函数 

 

 

 以及时间函数在不同数据库中的处理

 

 

还有字符的转换处理

 

 (四)分组聚合

3.1.9.3版本后支持分组聚合查询

        var commne = conn.QuerySet<Comment>()
                    .Where(x => x.Id > 0 && array1.Contains(x.Id) && x.Content.Replace("1", "2") == x.Content)
                    .Where(x => x.Id.In(array1))
                    .GroupBy(x => new { x.ArticleId })
                    .Having(x => Function.Sum(x.Id) >= 5)
                    .ToList(x => new
                    {
                        x.ArticleId,
                        test1 = Function.Sum(x.Id)
                    });

通过Function类点出函数,例如Function.Sum(字段)

 

 

 更多扩展敬请期待

 

Kogel.Dapper还支持linq和sql同时使用

已完成更加复杂查询条件或者连表关系,[详情请点击此处]

 

框架开源,完整框架源码可以去Github上下载:

https://github.com/kogel-net/Kogel.Dapper.Extension

如有问题也可以加QQ群讨论:

技术群 710217654


posted @ 2019-05-03 17:10  Kogel  阅读(64076)  评论(28编辑  收藏  举报