Sql Sugar使用仓储实现增删改查

1 按照《Sql Sugar生成实体类》生成实体类

2 创建控制台项目,通过nuge引入Sql Sugar

3 将实体类拷贝到项目中

4 创建仓储类Repository

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
namespace Repository
{
    public class Repository : SimpleClient where T : class, new()
    {
        public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
        {
            if (context == null)
            {
                base.Context = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.SqlServer,
                    InitKeyType = InitKeyType.Attribute,
                    IsAutoCloseConnection = true,
                    ConnectionString = "server=.;database=ZAS.WGT.Common;uid=sa;pwd=Server2012"
                });

                base.Context.Aop.OnLogExecuting = (s, p) =>
                {
                    Console.WriteLine(s);
                };
            }
        }

        /// 
        /// 扩展方法,自带方法不能满足的时候可以添加新方法
        /// 
        /// 
        public List CommQuery(string json)
        {
            T t = Context.Utilities.DeserializeObject(json);
            var list= base.Context.Queryable().WhereClass(t).ToList();
            return list;
        }
    }



}

5 新建服务类继承于仓储类

using Entitys;
using Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlSugarTest
{
    public class UserInfoService:Repository
    {
      
    }
}

6 通过调用服务类实现增删改查

using Entitys;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace SqlSugarTest
{
    class Program
    {
        static void Main(string[] args)
        {         


            var service = new UserInfoService();
            //查询
            var users = service.GetList();
            UserInfo ui = service.GetById(1);

            //增加
            service.Insert(new UserInfo() { UserName = "zhaosi", Password = "zhangsi", Role = 2 });


            //更新
            service.Update(new UserInfo() { Id = 6, Role = 1, Password = "666", UserName = "666"});

            //删除
            service.Delete(s => s.Id == 4);

            
        }
    }
}

你可能感兴趣的:(Sql,Sugar,sql,数据库,database)