接上文 项目架构开发:数据访问层之Logger

本章我们继续IRepository开发,这个仓储与领域模式里边的仓储有区别,更像一个工具类,也就是有些园友说的“伪仓储”,

这个仓储只实现单表的CURD与Query,都是通过主键ID或拉姆达表达式进行操作的,返回的都是单表的实体或实体集合,

多表的在IQuery接口中再讲;虽然如此,但是如果与“活动记录”开发模式搭配的话,会非常合适,可以减少开发的时间

及出错几率,更符合开发人员的类型调用习惯

IRepository.cs

     public interface IRepository<T> where T : class
{
void Add(T entity);
void AddBatch(IEnumerable<T> entitys);
void Update(T entity);
void Delete(T entity);
void Delete(string Id);
void Delete(int Id);
void Delete(Guid Id);
T Get(string Id);
T Get(Guid Id);
T Get(int Id);
T Get(T entity);
T Get(Expression<Func<T, bool>> func);
IEnumerable<T> GetAll();
IEnumerable<T> GetList(Expression<Func<T, bool>> where = null, Expression<Func<T, bool>> order = null);
Tuple<int, IEnumerable<T>> GetPage(Page page, Expression<Func<T, bool>> where = null, Expression<Func<T, bool>> order = null);
long Count(Expression<Func<T, bool>> where = null);
}

仓储的实现

这里我们只实现dapper的适配,EF有时间再搞吧

dapper大家应该都比较熟悉吧,不懂的朋友可以在园中搜索一下啊,很多案例

DapperRepository.cs

 using Dapper.Contrib.Extensions;
using LjrFramework.Common;
using LjrFramework.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions; namespace LjrFramework.Data.Dapper
{
public class DapperRepository<T> : IRepository<T> where T : class
{
protected IDbConnection Conn { get; private set; } public DapperRepository()
{
Conn = DbConnectionFactory.CreateDbConnection();
} public void SetDbConnection(IDbConnection conn)
{
Conn = conn;
} public void Add(T entity)
{
Conn.Insert<T>(entity);
} public void AddBatch(IEnumerable<T> entitys)
{
foreach (T entity in entitys)
{
Add(entity);
}
} public void Update(T entity)
{
Conn.Update(entity);
} public void Delete(T entity)
{
Conn.Delete(entity);
} public void Delete(string Id)
{
var entity = Get(Id);
if (entity == null) return; Delete(entity);
} public void Delete(int Id)
{
var entity = Get(Id);
if (entity == null) return; Delete(entity);
}
public void Delete(Guid Id)
{
var entity = Get(Id);
if (entity == null) return; Delete(entity);
} public T Get(T entity)
{
return Conn.Get<T>(entity);
} public T Get(Guid Id)
{
return Conn.Get<T>(Id);
} public T Get(string Id)
{
return Conn.Get<T>(Id);
} public T Get(int Id)
{
return Conn.Get<T>(Id);
} public T Get(Expression<Func<T, bool>> func)
{
var linqToWhere = new LinqToWhere<T>();
linqToWhere.Parse(func); return Conn.GetByFunc<T>(linqToWhere.Where, linqToWhere.KeyValuePairs);
} public IEnumerable<T> GetAll()
{
return Conn.GetAll<T>();
} public IEnumerable<T> GetList(Expression<Func<T, bool>> where = null, Expression<Func<T, bool>> order = null)
{
where = where.And(order); var linqToWhere = new LinqToWhere<T>();
linqToWhere.Parse(where); return Conn.GetListByFunc<T>(linqToWhere.Where, linqToWhere.KeyValuePairs);
} public Tuple<int, IEnumerable<T>> GetPage(Page page, Expression<Func<T, bool>> where = null, Expression<Func<T, bool>> order = null)
{
where = where.And(order); var linqToWhere = new LinqToWhere<T>();
linqToWhere.Parse(where); var multi = Conn.GetPage<T>(page.PageIndex, page.PageSize, linqToWhere.Order, linqToWhere.Where, linqToWhere.KeyValuePairs);
var count = multi.Read<int>().Single();
var results = multi.Read<T>(); return new Tuple<int, IEnumerable<T>>(count, results);
} public long Count(Expression<Func<T, bool>> where = null)
{
var linqToWhere = new LinqToWhere<T>();
linqToWhere.Parse(where); return Conn.Count<T>(linqToWhere.Where, linqToWhere.KeyValuePairs);
}
}
}

注意标红的那行,Conn的所有方法都是在命名空间(Dapper.Contrib.Extensions)下的扩展方法

我们看看其中的Insert实现方式,为什么直接传递T就可以,而不用写sql语句

可以看到,dapper后台是遍历实体的属性,最后也是拼凑成符合格式的sql语句;

这一点也可以自己扩展,有很大的便利性,所以他写在Extensions中

DbConnectionFactory.cs 也很简单,是dapper支持多数据库的工厂类

 public class DbConnectionFactory
{
private static readonly string connectionString;
private static readonly string databaseType; static DbConnectionFactory()
{
var collection = ConfigurationManager.ConnectionStrings["connectionString"];
connectionString = collection.ConnectionString;
databaseType = collection.ProviderName.ToLower();
} public static IDbConnection CreateDbConnection()
{
IDbConnection connection = null;
switch (databaseType)
{
case "system.data.sqlclient":
connection = new System.Data.SqlClient.SqlConnection(connectionString);
break;
case "mysql":
//connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
break;
case "oracle":
//connection = new Oracle.DataAccess.Client.OracleConnection(connectionString);
//connection = new System.Data.OracleClient.OracleConnection(connectionString);
break;
case "db2":
connection = new System.Data.OleDb.OleDbConnection(connectionString);
break;
default:
connection = new System.Data.SqlClient.SqlConnection(connectionString);
break;
}
return connection;
}
}

自此,dapper适配的仓储就完成了

我们在测试项目中看看效果,这里我们不在继续在基础设施里添加仓储了,用另一种方式:IOC

项目引用Autofac,用依赖出入来初始化IRepository<T>接口

测试仓储功能

 [TestClass]
public class DapperRepositoryTest
{
private IRepository<LoginUser> repository; public DapperRepositoryTest()
{
var builder = new ContainerBuilder();
builder.RegisterType<DapperRepository<LoginUser>>().As<IRepository<LoginUser>>(); var container = builder.Build();
repository = container.Resolve<IRepository<LoginUser>>();
} [TestMethod]
public void Add()
{
var loginUser = new LoginUser()
{
Id = Guid.NewGuid(),
LoginName = "lanxiaoke-" + Guid.NewGuid().ToString(),
Password = "mima1987",
IsEnabled = ,
CreateTime = DateTime.Now
}; repository.Add(loginUser); long count = repository.Count(t => t.LoginName == loginUser.LoginName); Assert.AreEqual(true, count == );
} [TestMethod]
public void Get()
{
var loginUser = new LoginUser()
{
Id = Guid.NewGuid(),
LoginName = "lanxiaoke-" + Guid.NewGuid().ToString(),
Password = "mima1987",
IsEnabled = ,
CreateTime = DateTime.Now
};
repository.Add(loginUser); var tmp = repository.Get(loginUser.Id);
Assert.AreEqual(loginUser.Id, tmp.Id); var tmp2 = repository.Get(w => w.Id == loginUser.Id && w.IsEnabled == loginUser.IsEnabled);
Assert.AreEqual(loginUser.Id, tmp2.Id);
}
...//限于篇幅,只写这么多了,大部分代码都差不多
}

注意这句:container.Resolve<IRepository<LoginUser>>(); 这句就是实现初始化IRepository<T>接口;

如何初始化呢?看上一句:builder.RegisterType<DapperRepository<LoginUser>>().As<IRepository<LoginUser>>(); 直接注册DapperRepository就可以了

其实这里也可以用配置的方式初始化IRepository<T>,这样就可以避免DapperRepository<T>与业务层耦合了

测试项目,我们就暂且这么写吧。

我们来看看效果

下边都是这次测试生成的数据

自此 IRepository 就开发完成了

项目架构开发系列

项目架构开发:数据访问层之Repository的更多相关文章

  1. 数据访问层之Repository

    数据访问层之Repository   接上文 项目架构开发:数据访问层之Logger 本章我们继续IRepository开发,这个仓储与领域模式里边的仓储有区别,更像一个工具类,也就是有些园友说的“伪 ...

  2. 企业级应用架构(三)三层架构之数据访问层的改进以及测试DOM的发布

    在上一篇我们在宏观概要上对DAL层进行了封装与抽象.我们的目的主要有两个:第一,解除BLL层对DAL层的依赖,这一点我们通过定义接口做到了:第二,使我们的DAL层能够支持一切数据访问技术,如Ado.n ...

  3. 项目架构开发:数据访问层之Cache

    数据访问层简单介绍 数据访问层,提供整个项目的数据访问与持久化功能.在分层系统中所有有关数据访问.检索.持久化的任务,最终都将在这一层完成. 来看一个比较经典的数据访问层结构图 大概可以看出如下信息 ...

  4. 项目架构开发:数据访问层之Logger

    接上文 项目架构开发:数据访问层之Cache 本章我们继续ILogger的开发 ILogger.cs public interface ILogger { void Info(object messa ...

  5. 项目架构开发:数据访问层之UnitOfWork

    接上文 项目架构开发:数据访问层之IQuery 本章我们继续IUnitOfWork的开发,从之前的IRepository接口中就可以看出,我们并没有处理单元事务, 数据CUD每次都是立即执行的,这样有 ...

  6. 项目架构开发:数据访问层之Query

    接上文 项目架构开发:数据访问层之Repository 上一章我们讲了IRepository接口,这张我们来讲IQuery 根据字面意思就可以知道,这次主要讲数据查询,上一章我们只针对单表做了查询的操 ...

  7. 随机获得MySQL数据库中100条数据方法 驾照题库项目 MVC架构 biz业务层的实现类 根据考试类型rand或order通过dao数据访问层接口得到数据库中100或全部数据

    package com.swift.jztk.biz; import java.util.Collections; import java.util.Comparator; import java.u ...

  8. asp.net/wingtip/创建数据访问层

    一. 什么是数据访问层 在wingtip项目中,数据访问层是对以下三者的总称:1. product类等数据相关的实体类(class)2. 数据库(database),对实体类成员的存储3. 上述二者的 ...

  9. servlet层调用biz业务层出现浏览器 500错误,解决方法 dao数据访问层 数据库Util工具类都可能出错 通过新建一个测试类复制代码逐步测试查找出最终出错原因

    package com.swift.jztk.servlet; import java.io.IOException; import javax.servlet.ServletException; i ...

随机推荐

  1. Add Strings Leetcode

    Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2 ...

  2. ThinkPHP 模板的包含、渲染、继承

    一.模板包含        <include file="完整模板文件名" />        <include file="./Tpl/default ...

  3. HDU-1102-Constructing Roads(并查集)

    题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1102 这题大意就不讲了, 这题很容易,不过我做的很不爽,一个下午,一直WA,后来才发现数组开小了 只开 ...

  4. Flex组件的生命周期

    组件实例化生命周期描述了用组件类创建组件对象时所发生的一系列步骤,作为生命周期的一部分,flex自动调用组件的的方法,发出事件,并使组件可见. 下面例子用as创建一个btn控件,并将其加入容器中 va ...

  5. Nginx之RTMP

    1. RTMP协议介绍 RTMP(Real Time Messaging Protocol)实时消息传送协议是Adobe Systems公司为Flash播放器和服务器之间音频.视频和数据传输开发的私有 ...

  6. Atom 编辑器系列视频课程

    此课程为 Atom 编辑器系列课程,主要介绍了 Atom 的高效开发技巧以及必备插件. 课程列表 Atom编辑器系列课程 #1 - Atom简介 Atom编辑器系列课程 #2 - 设置简介 Atom编 ...

  7. editormd使用教程

    对于现在的程序员来说,都需要一个快速写文章的语言,那么无非就是markdown了,市面上markdown编辑器并不多,而且也不怎么好用,现在推荐国内的比较牛逼的. 入门 建议先到官方看下如何使用,避免 ...

  8. 三分钟解读springmvc依赖

    长期以来都在写SSM框架的项目,却未能深入理解框架的搭建原理,而只是浅薄的理解前辈的架构,然后不断套用,项目做过几个,但框架的内涵却没有把握.小编打算今天从SpringMVC的依赖分析做起,一步步进行 ...

  9. Express之get,pos请求参数的获取

    Express的版本4.X Get query参数的获取 url假设:http://localhost:3000/users/zqzjs?name=zhaoqize&word=cool& ...

  10. 初识XMLHttpRequeset

    XMLHttpRequeset是什么 XmlHttpRequest,可扩展的超文本传输歇息.从字面上理解:xml,可扩展的标记语言:http,超文本传送协议:request,请求.XmlHttpReq ...