第一步:定有接口
标准的服务接口通常包含
- 添加或更新单条记录: ServiceResult AddOrUpdate(Entity model)
- 批量添加或更新单条记录: ServiceResult AddOrUpdate(IEnumerable<Entity> soucre)
- 获取单条记录: Entity GetSingle(long? id)
- 获取列表记录:List<Entity> GetList(Expression<Func<Entity, bool>> predicate = null)
- 获取分页记录:PagedList<Entity> GetPagedList(QueryModel query, Expression<Func<Entity, bool>> predicate = null)
- 删除记录: ServiceResult Delete(long? id);
已财务记录为例的示例代码:
/// <summary> /// 财务记录 /// </summary> public interface IBillService : IDynamicService { /// <summary> /// 添加或更新财务记录 /// </summary> /// <param name="entity"></param> /// <returns></returns> void AddOrUpdate(Bill entity); /// <summary> /// 批量添加或更新财务记录 /// </summary> /// <param name="soucre"></param> /// <returns></returns> void AddOrUpdate(IEnumerable<Bill> soucre); /// <summary> /// 获取一条财务记录 /// </summary> /// <param name="id">c财务记录ID</param> /// <returns></returns> Bill GetSingle(long? id); /// <summary> /// 获取财务记录列表 /// </summary> /// <param name="predicate">查询条件</param> /// <returns></returns> List<Bill> GetList(Expression<Func<Bill, bool>> predicate = null); /// <summary> /// 获取分页记录的财务记录 /// </summary> /// <param name="query">查询条件</param> /// <param name="predicate">查询条件</param> /// <returns></returns> PagedList<Bill> GetPagedList(QueryModel query, Expression<Func<Bill, bool>> predicate = null); /// <summary> /// 删除财务记录 /// </summary> /// <param name="id"></param> /// <returns></returns> void Delete(long? id); }
第二步:完成服务接口
public class BillService : ServiceBase, IBillService { public void AddOrUpdate(IEnumerable<Bill> soucre) { if (soucre == null) throw new ArgumentNullException(nameof(soucre)); foreach (var item in soucre) { AddOrUpdate(item); } } public void AddOrUpdate(Bill entity) { if (entity.Id > 0) { Repository<BillRepository>().UpdateSingle(entity); } else { Repository<BillRepository>().AddSingle(entity); } } public void Delete(long? id) { Repository<BillRepository>().Delete(r=>r.Id==id); } public List<Bill> GetList(Expression<Func<Bill, bool>> predicate = null) { throw new NotImplementedException(); } public PagedList<Bill> GetPagedList(QueryModel query, Expression<Func<Bill, bool>> predicate = null) { return Repository<BillRepository>().ReadMany(query, predicate); } public Bill GetSingle(long? id) { return Repository<BillRepository>().ReadSingle(e => e.Id == id); } }
注意实现:
- Add和Update方法 统一写到一起,不要分开用AddOrUpdate
- GetList方法传入Expression<Func<Bill, bool>>参数
- AddOrUpdate方法不需要再赋值了,默认会采用实体的默认值