.NET Core的SqlSugar上手使用小例子

開始直接建個空的WEB項目-建Controllers文件夾-開啓MVC-添加NuGet程序包SqlSugarCoresql

  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類:json

 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 + "\r\n" +
                                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();
        }
    }

直接在控制器操做便可:mvc

 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/Docapp

相關文章
相關標籤/搜索