- 在CM.Repository下新建上下文类DbContext
- 定义DbContext
DbContext.cs
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
namespace CM.Repository
{
public class DbContext<T> where T : class, new()
{
public DbContext()
{
var cnn = "server=127.0.0.1;uid=root;pwd=root;database=dotnetcms;sslmode=None";
Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = cnn,
DbType = DbType.MySql,
IsAutoCloseConnection = true,
});
TableClient = new SimpleClient<T>(Db);
}
public SqlSugarClient Db { get; private set; }
public SimpleClient<T> TableClient { get; private set; }
public static DbContext<T> Instance = new DbContext<T>();
}
}
- 之前在 (2)CM.Api项目创建Json包装类与数据库操作接口 中已经创建好了IRepository 基本接口的方法
- 创建它的实现类Repository
Repository.cs
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
namespace CM.Repository
{
public class Repository<T> : IRepository<T> where T : class, new()
{
public DbContext<T> Context = DbContext<T>.Instance;
public virtual bool Delete(dynamic id)
{
return Context.TableClient.Delete(id);
}
public bool Delete(Expression<Func<T, bool>> expression)
{
return Context.TableClient.Delete(expression);
}
public bool DeleteList(List<dynamic> ids)
{
return Context.TableClient.DeleteByIds(ids.ToArray());
}
public virtual bool DeleteList(string ids)
{
var list = ids.Split('_');
var idList = new List<dynamic>();
foreach (string j in list)
{
idList.Add(Convert.ToInt64(j));
}
return DeleteList(idList);
}
public virtual bool Exists(dynamic id)
{
return Context.Db.Queryable<T>().InSingle(id) != null;
}
public virtual List<T> GetList()
{
return Context.TableClient.GetList();
}
public List<T> GetList(Expression<Func<T, bool>> expression)
{
return Context.Db.Queryable<T>().Where(expression).ToList();
}
public List<T> GetList(string where)
{
return Context.Db.Queryable<T>().Where(where).ToList();
}
public virtual T GetModel(dynamic id)
{
return Context.TableClient.GetById(id);
}
public virtual T GetModel(Expression<Func<T, bool>> expression)
{
T model = null;
List<T> list = GetList(expression);
if (list.Count > 0) model = list[0];
return model;
}
public virtual List<T> GetPageList(int pageIndex, int pageSize)
{
return Context.Db.Queryable<T>()
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize)
.ToList();
}
public List<T> GetPageList(int pageIndex, int pageSize, string where)
{
return Context.Db.Queryable<T>().Where(where)
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize)
.ToList();
}
public List<T> GetPageList(int pageIndex, int pageSize, Expression<Func<T, bool>> expression)
{
return Context.Db.Queryable<T>().Where(expression)
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize)
.ToList();
}
public bool Insert(T obj)
{
return Context.Db.Insertable(obj).ExecuteCommandIdentityIntoEntity();
}
public bool Update(T obj)
{
return Context.TableClient.Update(obj);
}
}
}