sqlsugar使用

sqlsugar使用

sqlsugar是一款非常轻量级并且特别强大的ORM,支持常见的关系型数据库(Oracle , sqlserver , MySQL等等等等),本文示例的是SqlServer,其他数据库雷同。sqlsugar属于全自动型ORM,当然,你也可以拼接sql语句查询,下面都有讲解。这里就简单说一下用法,至于有何优势或者说需要更深层的挖掘,可能就需要您更多的摸索了。

## web MVC程序实现

 思路和流程如下
  1. 新建web MVC程序 ,我就命名WebApplication1好了
  2. 程序NuGet引入两个类库sqlsugar和Newtonsoft.Json,两种引入方法:第一种,程序包管理控制台依次输入Install-Package sqlsuga和Install-Package Newtonsoft.Json;第二种在管理解决方案NuGet程序包中依次搜索sqlsugar和Newtonsoft.Json然后安装。
  3. 新建一个文件夹,里面新建一个模型一个类, 类dbContext和模型test,下面会讲解,当然,文件夹和类名可以自己命名,模型的话是对应数据库表的,所以命名得和数据库表名一致。类dbContext用来连接数据库用。
  4. 调用dbContext类(第3点新建的),完成。
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Helper
{
    public class dbContext
    {
        private static SqlSugarClient _db = null;
        /// 
        /// test是数据库名
        /// 
        public static string ConnectionString = "Data Source=localhost;Initial Catalog=test;User id=sa;Password=123456";
        public static SqlSugarClient CretClient()
        {
            _db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = ConnectionString, //数据库连接字符串
                DbType = DbType.SqlServer, //必填
                IsAutoCloseConnection = false, //默认false
                InitKeyType = InitKeyType.Attribute
            });
            return _db;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Helper
{
    public partial class test
    {
        public int ID { get; set; }
        public string usernage { get; set; }
        public string password { get; set; }
    }
}
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Helper;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public static SqlSugarClient DbContext = dbContext.CretClient();
        public ActionResult Index()
        {
            var results = DbContext.GetSimpleClient<test>().GetList().Where(i => i.ID == 1);
            var sqlResults = DbContext.SqlQueryable<test>("select * from test where ID = 1").ToList();
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

你可能感兴趣的:(c#)