接上文 项目架构开发:数据访问层之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. PHP正则表达式验证是否含有中文

    判断是否 有中文. if (preg_match("/[\x7f-\xff]/", $string)) { echo "true"; }else{ echo & ...

  2. iOS 协议

    协议分为三部分:声明.引用.实现. 通常,声明协议和声明协议类型的属性都是在同一个类中.声明协议和声明协议作为属性在头文件中,引用在声明类的实现文件中.而实现协议则在其它类中.

  3. phpcms 杂乱总结

    1.根据catid 获取 栏目名称 $CATEGORYS = getcache('category_content_'.$siteid,'commons'); $name = {$CATEGORYS[ ...

  4. CSS的position设置

    CSS的position设置: <%@ page language="java" contentType="text/html; charset=UTF-8&quo ...

  5. Flex timer使用 keydown事件注册到stage

    Flex timer使用 keydown事件注册到stage: <?xml version="1.0" encoding="utf-8"?> < ...

  6. underscore 1.7.0 api

    它是这个问题的答案:“如果我在一个空白的HTML页面前坐下, 并希望立即开始工作, 我需要什么?“ http://www.css88.com/doc/underscore/#

  7. PWM(脉宽调制)——LED特效呼吸灯设计

    简述PWM PWM--脉宽调制信号(Pulse Width Modulation),它利用微处理器的数字输出来实现,是对模拟电路控制的一种非常有效的技术,广泛应用于测量.通信.功率控制与变化等许多领域 ...

  8. MySQL锁详解

    一.概述 数据库锁定机制简单来说就是数据库为了保证数据的一致性而使各种共享资源在被并发访问访问变得有序所设计的一种规则.对于任何一种数据库来说都需要有相应的锁定机制,所以MySQL自然也不能例外.My ...

  9. 【Android】 分享一个完整的项目,适合新手!

    写这个app之前是因为看了头条的一篇文章:http://www.managershare.com/post/155110,然后心想要不做一个这样的app,让手机计算就行了.也就没多想就去开始整了.   ...

  10. asp.net权限认证篇外:集成域账号登录

    在之前的我们已经讲过asp.net权限认证:Windows认证,现在我们来讲讲域账号登录, 这不是同一件事哦,windows认证更多的是对资源访问的一种权限管控,而域账号登录更多的是针对用户登录的认证 ...