Mysql open source framework Sqlsugar combined to develop a small demo

A, Sqlsugar Profile

There are great advantages 1. Performance

sqlsugar ORM is one of the best performance, with performance beyond Dapper, taking enough EMIT configuration dynamically compiled into an intermediate language set to complete performance binding entity, to the native level.

2. very powerful

In addition to EF can say is the biggest feature of ORM framework

Support DbFirst, CodeFirst, database maintenance, query chain, chain update, delete chain, chain insertion, entity attributes, complex model queries, ADO.NET. In particular, not batch cycle operation and other functions are genuine.

SqlSugar 4.0 version of the end of June to support SqlSever Core version, multi-database support is expected in July, August, 2010 to begin a distributed development of ORM. (3.x version has support for four databases, the relative stabilization simple)

3. The syntax is simple

Perfect syntax, you can kill all existing ORM framework

See detailed syntax triumph blog Sun Park  http://www.codeisbug.com/Doc/8

Second, it focuses on how to use mysql database to use in conjunction Sqlsugar

1. Create a new solution, a custom solution name and save path

2. At this point we need to add three packages, first find the tools = NuGet package "NuGet Package Manager => Management Solutions

3. Add the following order three packages

Newtonsoft.Json: pay attention to add a higher version of the best, otherwise there will be compatibility problems

 

Sqlsugar: This version should you choose the appropriate version according to your version of .Net Framework, and here I use the .Net Framework4.5 so I installed the sqlsugar5.0.0.8

 

MySql.Data

 

4. The preparatory work has been done, now you can start a text

A code affixed to the case, this is a class I a package of database operations, Example I using a single mode, but there is not the drawbacks of high concurrency

public class DBContext<T> where T : class, new()
    {
        public SqlSugarClient Db;
        private static DBContext<T> mSingle = null;
        public static DBContext<T> GetInstance()
        {
            if (mSingle == null)
                mSingle = new DBContext<T>();
            return mSingle;
        }
        protected DBContext()
        {  //通过这个可以直接连接数据库
            Db = new SqlSugarClient(new ConnectionConfig()
            {
                //可以在连接字符串中设置连接池pooling=true;表示开启连接池
                //eg:min pool size=2;max poll size=4;表示最小连接池为2,最大连接池是4;默认是100
                ConnectionString = "database='" + "BookShop" + "';Data Source = '" + "127.0.0.1" + "'; User Id = '" + "root" + "'; pwd='" + "1234" + "';charset='utf8';pooling=true",
                DbType = SqlSugar.DbType.MySql,//我这里使用的是Mysql数据库
                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 void Dispose()
        {
            if (Db != null)
            {
                Db.Dispose();
            }
        }
        public SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetList()
        {
            return CurrentDb.GetList();
        }

        /// <summary>
        /// 根据表达式查询
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetList(Expression<Func<T, bool>> whereExpression)
        {
            return CurrentDb.GetList(whereExpression);
        }


        /// <summary>
        /// 根据表达式查询分页
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel pageModel)
        {
            return CurrentDb.GetPageList(whereExpression, pageModel);
        }

        /// <summary>
        /// 根据表达式查询分页并排序
        /// </summary>
        /// <param name="whereExpression">it</param>
        /// <param name="pageModel"></param>
        /// <param name="orderByExpression">it=>it.id或者it=>new{it.id,it.name}</param>
        /// <param name="orderByType">OrderByType.Desc</param>
        /// <returns></returns>
        public virtual List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel pageModel, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
        {
            return CurrentDb.GetPageList(whereExpression, pageModel, orderByExpression, orderByType);
        }


        /// <summary>
        /// 根据主键查询
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetById(dynamic id)
        {
            return CurrentDb.GetById(id);
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(dynamic id)
        {
            if (string.IsNullOrEmpty(id.ObjToString))
            {
                Console.WriteLine(string.Format("要删除的主键id不能为空值!"));
            }
            return CurrentDb.Delete(id);
        }


        /// <summary>
        /// 根据实体删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(T data)
        {
            if (data == null)
            {
                Console.WriteLine(string.Format("要删除的实体对象不能为空值!"));
            }
            return CurrentDb.Delete(data);
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(dynamic[] ids)
        {
            if (ids.Count() <= 0)
            {
                Console.WriteLine(string.Format("要删除的主键ids不能为空值!"));
            }
            return CurrentDb.AsDeleteable().In(ids).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 根据表达式删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(Expression<Func<T, bool>> whereExpression)
        {
            return CurrentDb.Delete(whereExpression);
        }


        /// <summary>
        /// 根据实体更新,实体需要有主键
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Update(T obj)
        {
            if (obj == null)
            {
                Console.WriteLine(string.Format("要更新的实体不能为空,必须带上主键!"));
            }
            return CurrentDb.Update(obj);
        }

        /// <summary>
        ///批量更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Update(List<T> objs)
        {
            if (objs.Count <= 0)
            {
                Console.WriteLine(string.Format("要批量更新的实体不能为空,必须带上主键!"));
            }
            return CurrentDb.UpdateRange(objs);
        }

        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Insert(T obj)
        {
            return CurrentDb.Insert(obj);
        }


        /// <summary>
        /// 批量
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Insert(List<T> objs)
        {
            return CurrentDb.InsertRange(objs);
        }


        //可以扩展更多方法 
    }

5.还有就是需要有model类,就是跟数据库中表对应的model类,比如我这里是book和booktype,附加一段代码做个参考

    [SugarTable("Books")]//指定数据库中的表名,要对应数据库的表名,否则会出错
    public class Books
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//指定主键和自动增长
        public int Id { get; set; }
        public int  BId { get; set; }
        public string BName { get; set; }
        public int TypeId { get; set; }
    }

6.开始操作数据库了

           Books b = new Books() { BId = 2, BName = "西游记", TypeId = 2 };
            BookType bt = new BookType() {  TId= 3, TName = "健康"};

            if (DBContext<Books>.GetInstance().CurrentDb.Insert(b))
            {
                Console.WriteLine("books_添加成功!");
            }
            if (DBContext<BookType>.GetInstance().Db.Insertable(bt).ExecuteCommand() > 0)
            {
                Console.WriteLine("BookType_添加成功!");
            }

其他操作数据库的例子参考孙凯旋的博客园吧,附链接 http://www.codeisbug.com/Doc/8/1123

例子到这里就结束了,分享一下,我在做这个过程中遇到的问题:

1.因为我原本项目中已经存在程序包Newtonsoft.Json,而它的版本较低,当时忽略了版本问题,导致版本不兼容问题。后面升级之后就可以了。

2.犹豫项目需要高并发处理数据,所以我上边写的单例模式其实存在一定的问题,所以做了一定的修改,代码贴一下

  public class DBContext<T> where T : class, new()
    {
        public SqlSugarClient Db;

        /// <summary>
        /// 修改后的代码
        /// </summary>
        /// <returns></returns>
        public static DBContext<T> OpDB()
        {
            DBContext<T> dbcontext_t = new DBContext<T>();
            dbcontext_t.Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = "database='" + "bookshop" + "';Data Source = '" + "127.0.0.1" + "'; User Id = '" + "root" + "'; pwd='" + "1234" + "';charset='utf8';pooling=true",
                DbType = SqlSugar.DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
            return dbcontext_t;
        }

        protected DBContext()
        {
            Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = "database='" + "bookshop" + "';Data Source = '" + "127.0.0.1" + "'; User Id = '" + "root" + "'; pwd='" + "1234" + "';charset='utf8';pooling=true",
                DbType = SqlSugar.DbType.MySql,
                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 SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } }



        //可以扩展更多方法 
    }

ok,该demo的分享就到这了,如果有什么错误的地方欢迎指出,有不理解的也可以留言。

 

Guess you like

Origin www.cnblogs.com/guhuazhen/p/11096154.html