第一步 创建项目,并添加相关的组件包
创建.net core的项目过程和添加引用包这里我就不写出来了,自行解决。
第二步 创建数据层
1创建数据连接
第三步 创建仓储,为了便于以后的扩展建议多建一个类库用作自定义仓储,我这里快速就创建在数据层了
1定义仓储接口 接口定义未常用的操作方法就行了
2实现仓储业务
///
/// 仓储实现层
///
///
public class Repository
{
///
/// 构造参数
///
///
public Repository(IConfiguration configure):base(configure)
{
}
///
/// 添加数据
///
///
///
public int Add(T model)
{
return Db.Insertable(model).ExecuteCommand();
}
///
/// 添加数据并返回主键
///
///
///
public int RetuIdAdd(T model)
{
return Db.Insertable(model).ExecuteReturnIdentity();
}
///
/// 添加数据并返回插入的实体
///
///
///
public T RetuEntityAdd(T model)
{
return Db.Insertable(model).ExecuteReturnEntity();
}
///
/// 根据条件查询对象
///
///
///
public T DataItem(Expression
{
return Db.Queryable
}
///
/// 根据条件分页查询列表
///
///
///
///
///
public List
{
return Db.Queryable
}
///
/// 根据条件查询列表
///
///
///
public List
{
return Db.Queryable
}
///
/// 查询所有数据
///
///
public List
{
return Db.Queryable
}
///
/// 删除数据
///
///
///
public int Delete(Expression
{
return Db.Deleteable
}
///
/// 更新数据
///
///
///
public int Update(T model)
{
return Db.Updateable
}
public int Update(List
{
return Db.Updateable(list).ExecuteCommand();
}
///
/// 查询总记录数
///
///
///
public int DataCount(Expression
{
return Db.Queryable
}
///
/// 查询总记录数
///
///
///
public int DataCount(List
{
return Db.Queryable
}
///
/// 批量删除
///
///
///
public int Delete(dynamic[] ids)
{
return Db.Deleteable
}
}
第四步 关键点 在web层的Startup注入仓储和业务层
//业务层注入
Assembly assemblys = Assembly.Load("QuestionnaireSurvey.BLL");
Assembly assemblysInterFace = Assembly.Load("QuestionnaireSurvey.IBLL");
var typesInterface = assemblysInterFace.GetTypes();
var typesImpl = assemblys.GetTypes();
foreach (var item in typesInterface)
{
var name = item.Name.Substring(1);
string implBLLImpName = name + "Server";
var impl = typesImpl.FirstOrDefault(w => w.Name.Equals(implBLLImpName));
if (impl != null)
{
services.AddTransient(item, impl);
}
}
//注入数据层
services.AddTransient(typeof(DbSqlContext));
//注入仓储
services.AddTransient(typeof(IRepository<>), typeof(Repository<>));
第五步 调用
///
/// 业务层 处理业务
///
public class ArtcleBLLServer : IArtcleBLL
{
///
/// 声明要调用的仓储
///
public IRepository
///
/// 构造参数
///
///
public ArtcleBLLServer(IRepository
{
_respond = respond;
}
///
/// 查询所有数据
///
///
public List
{
return _respond.GetList();
}
}
简单的.net core api+仓储+SqlSugar MOR框架就搭建好了