zoukankan      html  css  js  c++  java
  • SqlSugar入门级教程+实例 (.net core下的)

    官方参考:http://www.codeisbug.com/Doc/8

    前言:这应该是目前最好用的ORM框架之一了,而且支持.net core,网上除了官方文档其他参考就少了点,自己整理了一下,大致包括:

             · 概念

             ·  一个小demo(会涉及到T4模板生成Model)

             · 常见用法(增删改查)

    数据库是sqlserver2012,vs2017版本的,其他还有什么想到再补充。

    (2019-12-15更新:大半年没上博客今天看到邮件评论提醒上来看一下,当时没有想到这篇笔记会有那么多人看,我现在自己回看实在汗颜,写的啥玩意儿,尤其是配置那块,当时也是copy的项目代码,再后来因为离职也忘了更新代码,而现在我已经用不到sqlsugar了,不过也正因为如此,才更觉得sqlsugar好用,对于一些没有自己框架的小公司小项目其实是个不错的选择。年底我会抽空重新写个项目,这篇权且看看好了)

    一:概念

    1.优势

    支持.NET 4.0+ .NET CORE

    支持主流数据库:SQL Server,MySql,Oracle,Sqlite等;

    2.安装

    Nuget直接搜索

    项目是Core安装sqlSugarCore版本,.Net安装sqlSugar

    3.连接

    通过参数ConnnectionConfig创建连接,ConnectionConfig6个属性:

    1. ConnectionString: 连接字符串 (必填)

    2. Data Type: 数据库类型 (必填)

    3. IsAutoCloseConnection: 是否自动释放数据库,默认false

    4. InitKeyType: 读取主键和自增列信息的方式,默认SystemTable

    5. More Settings: 全局设置

    6. ConfigureExternalServices: 可以扩展你想要的序列化方式和缓存方式等服务

    例:

    SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()

    {

    ConnectionString = Config.ConnectionString,

      DbType = DbType.SqlServer,         

      IsAutoCloseConnection = true,       

      InitKeyType = InitKeyType.SystemTable  

    });

    不过后面的版本有变动,以下是4.6.1版本的:

    SqlSugar对象不能是静态变量,但可以是静态属性。

    例:

    Public static SqlSugarClient Instance

    {

    get => new SqlSugarClientxx;
    ]

    Var db = .Instance;

    db.Queryable<T>().ToList;

    二:项目实例

    1:新建项目:.net core

    我选择空模板,其他的也行,建议MVC

    2.添加两个类库(我习惯分层写,也可以不分层)

    一定是添加不要在上面新建

    3.在ORM层安装sqlSugar,.net选第一个就好了

    4.使用T4模板生成Model

    a.先在sql server中建好表,数据库名:SqlSugarDemo

    [表Student]:

    b.右键项目->添加文本模板,名字随便起,后缀tt

    c.写好tt模板保存一下就会刷新出model,Teacher和Course表先不用管

    (tt模板里的内容自行百度,我照搬公司的就不贴了,其实都差不多,SqlSugarBase.cs是下一步建的,我截图晚了)

    5.在ORM层新建SqlSugarBase类,用来提供DB访问对象,代码可以参考官方文档:(代码已修正,本页最底下

    using SqlSugar;
    
    namespace SqlSugarDemo.ORM
    {
        public class SqlSugarBase
        {
            public static string DB_ConnectionString { get; set; }
      
            public static SqlSugarClient DB
            {
                get => new SqlSugarClient(new ConnectionConfig()
                {
                        ConnectionString = DB_ConnectionString,
                        DbType = DbType.SqlServer,
                        IsAutoCloseConnection = true,
                        InitKeyType = InitKeyType.SystemTable,
                        IsShardSameThread = true
                    }
                );           
            }
        }
    }
    SqlSugarBase

    6.配置Startup.cs和appsettings.json,跟我一样建空模板的要在Web层(API)手动添加:(代码已修正,本页最底下

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using SqlSugarDemo.ORM;
    
    namespace SqlSugarDemo
    {
        public class Startup
        {
            readonly private IConfiguration _Configuration;
            public Startup(IConfiguration configuration)
            {
                this._Configuration = configuration;
            }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
    
                SqlSugarBase.DB_ConnectionString = this._Configuration.GetConnectionString("connectionString");   //为数据库连接字符串赋值
    
            }
    
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                app.UseStaticFiles();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
    
                    routes.MapRoute(
                        name: "default1",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
    
            }
    
    
            //public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            //{
            //    if (env.IsDevelopment())
            //    {
            //        app.UseDeveloperExceptionPage();
            //    }
    
            //    app.Run(async (context) =>
            //    {
            //        await context.Response.WriteAsync("Hello World!");
            //    });
            //}
        }
    }
    startup.cs

    以上代码有参考:https://www.cnblogs.com/kuangliwen/p/7895646.html

      "connectionString": "Server=127.0.0.1;Database=SqlSugarDemo;Integrated Security=False;User ID=sa;Password=sa;",
      "Logging": {
        "IncludeScopes": false,
        "Debug": {
          "LogLevel": {
            "Default": "Warning"
          }
        },
        "Console": {
          "LogLevel": {
            "Default": "Warning"
          }
        }
      }
    }
    appsettings.json

    7.添加逻辑代码和控制类(可以不分开写)

    在Service层右键添加HomeService.cs

    using SqlSugarDemo.ORM;
    using SqlSugarDemo.ORM.Entity;
    using System.Collections.Generic;
    
    namespace SqlSugarDemo.Service
    {
        public class HomeService : SqlSugarBase
        {
            public List<Student> GetList()
            {
                return DB.Queryable<Student>().ToList();
            }
        }
    }
    HomeService.cs

    DB.Queryable<Student>().ToList();   相当于select * from Student

    在Web层右键添加HomeController.cs(代码已修正,本页最底下

    using Microsoft.AspNetCore.Mvc;
    using SqlSugarDemo.Service;
    
    namespace SqlSugarDemo.API
    {
        public class HomeController : Controller
        {
            readonly HomeService _HomeService;
            public HomeController(HomeService homeService)
            {
                _HomeService = homeService;
            }
    
            [HttpGet]
            public IActionResult Index()
            {
                var result =   _HomeService.GetList();
                ViewBag.Result = result;
                return View();
            }
        }
    }
    HomeController.cs

    8.最后别忘了添加Index页面

    最终项目结构:

    我觉得这个项目结构不是很好,随意看看

     编译通过,运行我报500的错误(惨兮兮),原因还在找,可能第6步有点问题,所以不能验证结果,反正过程大致是这么个过程。

    //0810更新:数据库连接有问题,稍后修改

    //0813更新:全部代码已修改完毕,详见底部

    三:SqlSugar常用方法总结

    先上之前的三张表:

    [Student]

    [Teacher]

    [Course]

    很简单的三张表,Id都是主键自增,其中Student.CourseId = Course.Code = Teacher.CourseId

     【查询】

    1. 查询所有

    var result = DB.Queryable<Student>().ToList();

    相当于 :

    select * from Student;

    2. 跟据主键查询:id为方法参数

    var result =  DB.Queryable<Student>().InSingle(id);

    相当于 :

    select * from Student where Id = id;

    3. 根据给定的字段查询:name为方法参数

    var result = DB.Queryable<Student>().Where(s => s.Name == name);

    相当于:

    select * from Student where Name = name;

    4. 模糊查询:方法参数key为关键字

    var result = DB.Queryable<Student>().Where(s => s.Name.Contains(key)).ToList();

    相当于:

    select * from Student where Name  like ‘%key%’;

    5. 双表查询

    var result = DB.Queryable<Student, Teacher>((a, b) => new object[] {
                 JoinType.Left,a.CourseId==b.CourseId})
                 .Select((a, b) => new { Student = a.Name, Teacher = b.Name }).ToList();

    以上将结果返回匿名对象,要是返回实体对象,第三行new 一个model就行了。

    相当于:

    select Student.Name student,Teacher.Name teacher

    from Student

    left join Teacher

    on Student.CourseId = Teacher.CourseId;

    6. 三表查询,根据给定id查询学生姓名,老师和课程名称

    var result = DB.Queryable<Student, Teacher, Course>((a, b, c) => new object[] {
                            JoinType.Left,a.CourseId == b.CourseId,
                            JoinType.Left,b.CourseId == c.Code
                        })
                        .Where(a => a.Id == id)
                        .Select((a, b, c) => new  { Student = a.Name, Teacher = b.Name,Course = c.name }).ToList();

    以上同样返回匿名对象

    相当于:

    select Student.Name student,Teacher.Name teacher,Course.name course  

    from Student

    left join Teacher

    on Student.CourseId = Teacher.CourseId

    left join Course

    on Course.Code = Teacher.CourseId

    where Student.Id = id;

    7. 分页,以第四条为例,方法参数pageIndex为页数,pageSize为条数

    var result = DB.Queryable<Student>().Where(s => s.Name.Contains(key)).ToPageList(pageIndex, pageSize).ToList();

    【删除】

    1. 根据主键删除,id为方法参数

    var result = DB.Deleteable<Student>().In(id).ExecuteCommand();

    相当于:

    Delete from Student where Id = id;

    2. 根据主键批量删除ids为方法参数

    var result = DB.Deleteable<Student>().In(ids).ExecuteCommand();

    3. 根据给定字段删除name为方法参数

    var result = DB.Deleteable<Student>().Where(s => s.Name == name).ExecuteCommand();

    相当于:

    Delete from Student where Name = name;

    4. 批量删除,key为关键字

    var result = DB.Deleteable<Student>().Where(s => s.Name.Contains(key)).ExecuteCommand();

    相当于:

    Delete from Student where Name like’%a%’;

     【添加】

    以向表Student添加数据为例:

     
    public bool Insert()
            {
                Student model = new Student();
                model.StuId = 8;
                model.Name = "abc";
                model.CourseId = 2;
                var test = DB.Insertable(model).ExecuteCommand();
                return test > 0;
            }

    ps:关键就是:DB.Insertable(model).ExecuteCommand()   这一句。

    <StudentModel>不一定要写,可以使用匿名对象;

    model赋值也可以放到添加方法里,比如:

    var test = DB.Insertable(new StudentModel

    {

    Name = "abc",

    //这里想要添加几个字段就写几个

    }).ExecuteCommand()

    【更新】

    跟添加类似,DB.Insertable(model).ExecuteCommand()  改为  DB.Updateable(model).ExecuteCommand();



    代码修改:

    Startup.cs:

    public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
            public IConfiguration Configuration { get; }
    
            public void ConfigureServices (IServiceCollection services)
            {
                services.AddMvc();
            }
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                app.UseStaticFiles();
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }

    SqlSuagrBase:(连接字符串本来应该在appsettings里的,这个示范不太好,不过作为小demo就不考虑那么多了)

    public abstract class SqlSugarBase
        {
            public SqlSugarClient DB => GetInstance();
    
            SqlSugarClient GetInstance()
            {
                string connectionString = "Server=127.0.0.1;Database=SqlSugarDemo;Integrated Security=False;User ID=sa;Password=sa;";
    
                var db = new SqlSugarClient(
                    new ConnectionConfig
                    {
                        ConnectionString = connectionString,
                        DbType = DbType.SqlServer,
                        IsShardSameThread = true
                    }
                );
                return db;
            }
        }

    Home Controller:这里把Index删了,重新写了查询方法,View里面的Index也可以不用了。

     [HttpGet]
            public List<Student> GetList()
            {
                var result = _HomeService.GetList();
                return result;
            }

    代码到这里就结束了,下面我添加了一个单元测试来测试这个方法(引用Xunit),测试通过。

    代码我整理一下再贴上来。

  • 相关阅读:
    jquery 代码搜集
    Windows Server 2008中安装IIS7.0
    javascript 判断两个日期之间的天数 兼容ie,firefox
    jquery选择器大全
    原始ajax方式调用asp.net后台方法
    JavaScript及C# URI编码详解
    利用JQuery直接调用asp.net后台方法
    C#操作XML小结_转载
    从bnbt tracker源码分析bt客户端与traker的通信
    传说中的神器: shared_ptr/weak_ptr/scoped_ptr
  • 原文地址:https://www.cnblogs.com/rulasann/p/9438654.html
Copyright © 2011-2022 走看看