zoukankan      html  css  js  c++  java
  • .NET Core的SqlSugar上手使用小例子

    开始直接建个空的WEB项目-建Controllers文件夹-开启MVC-添加NuGet程序包SqlSugarCore

      public class Startup
        {
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();   //注册mvc服务
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
               
                app.UseMvc(routes=> {     //开启mvc
                    routes.MapRoute(
                        name:"default",
                        template:"{controller=Home}/{action=Index}/{id?}"
                        );
                });
            }
        }

    把数据库的连接语句写到appsettings.json里面:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "DBSetting": {
        "ConnectString": "server=.;database=test_core;uid=sa;pwd=123"
    
      },
      "AllowedHosts": "*"
    }

    创建BaseHelper类:

     public class BaseHelper
        {
            public SqlSugarClient db;
    
            static IConfiguration configure = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build();
    
            private static readonly string _connectionstring = configure["DBSetting:ConnectString"];
           // public BaseHelper(string connectionString)
            public BaseHelper()
            {
                 db = new SqlSugarClient(
                        new ConnectionConfig()
                        {
                            ConnectionString = _connectionstring,
                            DbType = DbType.SqlServer,//设置数据库类型
                            IsAutoCloseConnection = true,//自动释放数据务,如果存在事务,在事务结束后释放
                            InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
                        });
    
                //用来打印Sql方便你调式    
                db.Aop.OnLogExecuting = (sql, pars) =>
                                {
                                    Console.WriteLine(sql + "
    " +
                                    db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                                    Console.WriteLine();
                                };
            }
            public SqlSugarClient GetDb()
            {
                return db;
            }
    
            public bool InsertInto<T>(T obj) where T : class, new()
            {
                return db.Insertable(obj).ExecuteCommandIdentityIntoEntity();
            }
    
            public int UpdateInfo<T>(Expression<Func<T, bool>> set, Expression<Func<T, bool>> where) where T : class, new()
            {
                return db.Updateable<T>().SetColumns(set).Where(where).ExecuteCommand();
            }
        }

    直接在控制器操作即可:

     public class HomeController : Controller
        {
            private static  SqlSugarClient _db = new BaseHelper().GetDb();
            private SimpleClient<Student> db = new SimpleClient<Student>(_db);
            public IActionResult Index()
            {
                //db.Insert(new Student()
                //{
                //    ClassId = 113,
                //    Name = "小明"
                //});
    
                //_db.Insertable(new Student()  {ClassId = 1,Name = "小高"}).ExecuteCommandIdentityIntoEntity();
    
                //var re = _db.Updateable(new Student() { ClassId=2, Name = "小梅" }).Where(p=>p.ClassId==2).ExecuteCommand();   //更新全部
    
                //_db.Updateable<Student>().SetColumns(p=>p.Name=="小小").Where(p => p.ClassId == 2).ExecuteCommand();   //更新指定字段
    
                //_db.Deleteable<Student>().Where(p => p.Name == "2").ExecuteCommand(); //删除
    
                UpdateInfo<Student>(p=>p.Name=="大大",p=>p.ClassId==2);
    
                new BaseHelper().InsertInto<Student>(new Student()
                {
                    ClassId = 113,
                    Name = "小明"
                });
                return View();
            }
            public bool InsertInto<T>(T obj) where T : class, new()
            {
                return _db.Insertable(obj).ExecuteCommandIdentityIntoEntity();
            }
            public int UpdateInfo<T>(Expression<Func<T, bool>> set, Expression<Func<T, bool>> where) where T : class, new()
            {
                return _db.Updateable<T>().SetColumns(set).Where(where).ExecuteCommand();
            }
        }

     还有很多可以直接使用的方法,可以去官网看看 => http://www.codeisbug.com/Home/Doc

  • 相关阅读:
    Arcmap软件报错:This application cannot run under a virtual machine arcmapr, 但是你并没有使用虚拟机
    Sql server 2008 作业失败通知邮件配置
    能drag和resize的DIV,目的是做一个类似于数据库视图设计器
    Type.GetType()与System.Web.Compilation.BuildManager.GetType()
    让你的实体字段和页面上的控件映射,自动绑定 ObjectBinding1.0
    利用Log Explor来恢复误用delete 、update了的数据
    破解版果冻手机动画主题for WM5 & WM6
    封装一个图片轮换的web控件
    利用Lucene.net对附件做搜索
    关于TransactionScope分布式事务在Oracle下的运作
  • 原文地址:https://www.cnblogs.com/ya-jun/p/11661500.html
Copyright © 2011-2022 走看看