在DDD.Domain工程文件夹Repository下创建RequestPage类:

  public class RequestPage
{
public RequestPage(int pagesize, int currentpage, string orderproperty, string order)
{
this.PageSize = pagesize;
this.CurrentPage = currentpage;
this.Orderproperty = orderproperty;
this.Order = order;
} public int PageSize { get; }
public int CurrentPage { get; }
public string Orderproperty { get; }
public string Order { get; }
}

在 Repository文件夹IRepository接口中定义:

  //返回聚合根分页的方法
List<TAggreateRoot> GetByConditionPages(Expression<Func<TAggreateRoot, bool>> condition,
RequestPage request, out int totalcount);
List<TAggreateRoot> GetByConditionPages(List<Conditions> condition,
RequestPage request, out int totalcount); List<TDTO> GetByConditionPages<TDTO>(Expression<Func<TAggreateRoot, bool>> condition,
RequestPage request, out int totalcount);
List<TDTO> GetByConditionPages<TDTO>(List<Conditions> condition,
RequestPage request, out int totalcount);

在DDD.Repository工程ResultPage类中:(结果集)

 public class ResultPage<T> : IQueryable<T>
{
public ResultPage(int totalpages, int totalcounts, int currentpage, List<T> data)
{
this.TotalPages = totalpages;
this.TotalCounts = totalcounts;
this.CurrentPage = currentpage;
this.Data = data;
} public int TotalPages { get; }
public int TotalCounts { get; }
public int Pagesize { get; }
public int CurrentPage { get; }
public List<T> Data { get; } public Type ElementType
{
get
{
return typeof(T); }
} public Expression Expression
{
get;
} public IQueryProvider Provider
{
get;
} public IEnumerator<T> GetEnumerator()
{
return Data.GetEnumerator();
} IEnumerator IEnumerable.GetEnumerator()
{
return Data.GetEnumerator();
}
}

在EFRepository中实现分页的方法:

public List<TAggreateRoot> GetByConditionPages(List<Conditions> condition, RequestPage request, out int totalcount)
{
return GetByConditionPages(WhereLamdaConverter.Where<TAggreateRoot>(condition), request, out totalcount);
} public List<TAggreateRoot> GetByConditionPages(Expression<Func<TAggreateRoot, bool>> condition, RequestPage request, out int totalcount)
{
var query = orderdbcontext.Set<TAggreateRoot>().Where(condition);
var skip = (request.CurrentPage - 1) * request.PageSize;
var take = request.PageSize;
var queryresult =
request.Order == "ASC" ? query.OrderBy(p => new { Order = request.Orderproperty })
.Skip(skip).Take(take) :
query.OrderByDescending(p => new { Order = request.Orderproperty })
.Skip(skip).Take(take);
totalcount = query.Count(); return new ResultPage<TAggreateRoot>(totalcount / request.PageSize, totalcount,
request.CurrentPage, queryresult.ToList()).ToList();
} public List<TDTO> GetByConditionPages<TDTO>(List<Conditions> condition, RequestPage request, out int totalcount)
{
return GetByConditionPages<TDTO>(WhereLamdaConverter.Where<TAggreateRoot>(condition), request, out totalcount);
} public List<TDTO> GetByConditionPages<TDTO>(Expression<Func<TAggreateRoot, bool>> condition, RequestPage request, out int totalcount)
{
var query = orderdbcontext.Set<TAggreateRoot>().Where(condition);
var skip = (request.CurrentPage - 1) * request.PageSize;
var take = request.PageSize;
var queryresult =
request.Order == "ASC" ? query.OrderBy(p => new { Order = request.Orderproperty })
.Skip(skip).Take(take) :
query.OrderByDescending(p => new { Order = request.Orderproperty })
.Skip(skip).Take(take);
totalcount = query.Count();
var queryresults = queryresult.ToList();
var queryresultdtos = new List<TDTO>();
if (totalcount > 0)
{
foreach (var q in queryresults)
{
var queryresultdto = Mapper.Map<TAggreateRoot, TDTO>(q);
queryresultdtos.Add(queryresultdto);
}
}
return new ResultPage<TDTO>(totalcount / request.PageSize, totalcount, request.CurrentPage,
queryresultdtos).ToList();
}

在DDD.Infrastructure中新建LamdaFilterConvert(做筛选的转化器):--Conditions

public class Conditions
{
//具体插叙的字段
public string Field { get; set; }
//操作符
public string Operator { get; set; }
//字段的值
public string Value { get; set; }
//字段查询组合的关系
public string Relation { get; set; }
//把界面传的值转成List集合
public static List<Conditions> BuildConditions(string[] fields, string[] operators, string[] values,
string[] relations)
{
var conditions = fields.Select((t, i) => new Conditions
{
Field = t,
Operator = operators[i],
Value = values[i],
Relation = relations[i]
}).ToList();
return conditions;
}
}

带有where的Lambda表达式转换器:

 public static class WhereLamdaConverter
{
private class ParameterReplacer : ExpressionVisitor
{
public ParameterExpression ParameterExpression { get; private set; } public ParameterReplacer(ParameterExpression paramExp)
{
this.ParameterExpression = paramExp;
} public Expression Replace(Expression exp)
{
return this.Visit(exp);
} protected override Expression VisitParameter(ParameterExpression p)
{
return this.ParameterExpression;
}
} public static Expression<Func<T, bool>> True<T>()
{
return item => true;
} public static Expression<Func<T, bool>> False<T>()
{
return item => false;
} public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expLeft, Expression<Func<T, bool>> expRight)
{
var candidateExpr = Expression.Parameter(typeof(T), "item");
var parameterReplacer = new ParameterReplacer(candidateExpr); var left = parameterReplacer.Replace(expLeft.Body);
var right = parameterReplacer.Replace(expRight.Body);
var body = Expression.And(left, right); return Expression.Lambda<Func<T, bool>>(body, candidateExpr);
} public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expLeft, Expression<Func<T, bool>> expRight)
{
var candidateExpr = Expression.Parameter(typeof(T), "item");
var parameterReplacer = new ParameterReplacer(candidateExpr);
var left = parameterReplacer.Replace(expLeft.Body);
var right = parameterReplacer.Replace(expRight.Body);
var body = Expression.Or(left, right);
return Expression.Lambda<Func<T, bool>>(body, candidateExpr);
}
public static Expression<Func<T, bool>> Parse<T>(string member, string logic, string matchValue)
{
if (string.IsNullOrEmpty(member))
{
throw new ArgumentNullException("member");
}
PropertyInfo keyProperty;
ParameterExpression pExp;
keyProperty = typeof(T).GetProperties().FirstOrDefault(item => item.Name.ToLower().Equals(member.Trim().ToLower()));
pExp = Expression.Parameter(typeof(T), "p"); if (keyProperty == null)
{
throw new ArgumentException("member不存在");
} Expression memberExp = Expression.MakeMemberAccess(pExp, keyProperty);
if (logic != "Contains")
{
bool memberIsNullableType = keyProperty.PropertyType.IsGenericType && keyProperty.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>); if (memberIsNullableType)
{
memberExp = Expression.MakeMemberAccess(memberExp, keyProperty.PropertyType.GetProperty("Value"));
} Type valueType = keyProperty.PropertyType;
if (memberIsNullableType == true)
{
valueType = valueType.GetGenericArguments().FirstOrDefault();
} object value = matchValue;
if (valueType == typeof(string) == false)
{
if (valueType != null)
value = valueType.GetMethod("Parse", new[] { typeof(string) }).Invoke(null, new[] { value });
} var valueExp = Expression.Constant(value, valueType); var expMethod = typeof(Expression).GetMethod(logic, new Type[] { typeof(Expression), typeof(Expression) }); var body = expMethod.Invoke(null, new object[] { memberExp, valueExp }) as Expression;
var lamdaexpression = Expression.Lambda(body, pExp) as Expression<Func<T, bool>>;
return lamdaexpression;
}
else
{
MethodCallExpression body = null;
body = Expression.Call(memberExp, typeof(string).GetMethod(logic), Expression.Constant(matchValue, typeof(string)));
var lamdaexpression = Expression.Lambda(body, pExp) as Expression<Func<T, bool>>;
return lamdaexpression;
}
} public static Expression<Func<T, bool>> Where<T>(List<Conditions> conditions)
{
Expression<Func<T, bool>> expression = null;
if (conditions != null && conditions.Count > 0)
{
var firstexpression =
Parse<T>(conditions[0].Field, conditions[0].Operator, conditions[0].Value);
if (conditions.Count <= 1)
return firstexpression;
for (var i = 1; i < conditions.Count; i++)
{
var rightexpression =
Parse<T>(conditions[i].Field, conditions[i].Operator, conditions[i].Value);
expression = conditions[i - 1].Relation.ToUpper().Equals("AND")
? firstexpression.And(rightexpression)
: firstexpression.Or(rightexpression);
}
}
return expression;
} }

把映射的代码移到DDD.Application工程ProductAppService类中:

  IRepository<Product> productrepository = ServiecLocator.Instance.GetService(typeof(IRepository<Product>))
as IRepository<Product>; Product product;
//public void CreateProduct(string productname, string color, string size,
// int count, decimal unitprice, string categoryname, string description)
//{
// product.CreateProduct(productname, color, size, count, unitprice, categoryname, description);
// context.Commit();
//} public ProductAppService()
{
product = new Product(productrepository);
//完成映射的创建
ProductMapping();
}
//在调用构造函数的时候完成映射的创建
private void ProductMapping()
{
//从界面的DTO持久化领域对象
var mapin = Mapper.CreateMap<ProductDTO, Product>();
//指定属性的对应关系
mapin.ConstructProjectionUsing(p => new Product
{
ProductName = p.Name,
Size = p.Size,
Color = p.Color,
Count = p.Amount,
UnitPrice = p.UnitPrice,
ProductCategory = new ProductCategory
{
Id = Guid.NewGuid(),
CategoryName = p.PCategoryName,
Description = p.PDescription
}
});
//返回界面的东西
var mapout = Mapper.CreateMap<Product, ProductDTO>();
mapout.ConstructProjectionUsing(p => new ProductDTO
{
Name = p.ProductName,
Size = p.Size,
Color = p.Color,
UnitPrice = p.UnitPrice,
PCategoryName = p.ProductCategory.CategoryName,
PDescription = p.ProductCategory.Description,
Amount = p.Count
});
}   /// <summary>
        /// 被前端调用的方法
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="request"></param>
        /// <param name="totalcount"></param>
        /// <returns></returns>
        public List<ProductDTO> GetProductDTOSByCondition(List<Conditions> conditions,
            RequestPage request, out int totalcount)
        {
            return productrepository.GetByConditionPages<ProductDTO>(conditions, request,
               out totalcount);
        }

DDD领域模型查询方法实现(八)的更多相关文章

  1. 编写高质量JS代码的68个有效方法(八)

    [20141227]编写高质量JS代码的68个有效方法(八) *:first-child { margin-top: 0 !important; } body>*:last-child { ma ...

  2. J2EE进阶(十七)Hibernate中常用的HQL查询方法(getHibernateTemplate())

    J2EE进阶(十七)Hibernate中常用的HQL查询方法(getHibernateTemplate())   当我们使用Hibernate进行数据的CRUD操作时,利用模版进行操作不失为一种方法. ...

  3. DDD领域模型和充血对象

    DDD领域模型 官方说法 领域驱动设计,它是对面向对象的的分析和设计(OOAD,Object Orient Analysis Design)的一个补充,对技术框架进行了分层规划,同时对每个类进行了策略 ...

  4. getHibernateTemplate()(Spring中常用的hql查询方法)

    Spring中常用的hql查询方法(getHibernateTemplate()) --------------------------------- 一.find(String queryStrin ...

  5. tp5 中 model 的查询方法

    实例化模型后调用查询方法,可以写任何想要的查询(推荐) public function select(){ $user = model('User'); $data = $user -> ) - ...

  6. 【Java EE 学习 17 下】【数据库导出到Excel】【多条件查询方法】

    一.导出到Excel 1.使用DatabaseMetaData分析数据库的数据结构和相关信息. (1)测试得到所有数据库名: private static DataSource ds=DataSour ...

  7. <五>JDBC_利用反射及JDBC元数据编写通用的查询方法

    此类针对javaBean类写了一个通用的查询方法,List<javaBean> 通用查询更新中...:通过学习,深刻体会到学会反射就等于掌握了java基础的半壁江山! 一.使用JDBC驱动 ...

  8. Thinkphp回顾之(四)查询方法深入学习

    本次讲的查询方法主要有:表达式查询,模糊查询,between语句,in语句,区间查询,统计数据,普通方式查询,但大多数都只是引入数组而已,明白了第一个,其他的也就差不多全明白了,唯一要注意的是在后台中 ...

  9. MyBaits一对一的查询方法

    MyBaits一对一的查询方法 一:表数据与表结构 CREATE TABLE teacher( t_id INT PRIMARY KEY AUTO_INCREMENT, t_name ) ); CRE ...

随机推荐

  1. ruby pluck用法,可以快速从数据库获取 对象的 指定字段的集合数组

    可以快速从数据库获取 对象的 指定字段的集合数组 比如有一个users表,要等到user的id数组: select id from users where age > 20; 要实现在如上sql ...

  2. 【JUC】CopyOnWriteArrayList

    写入时复制(CopyOnWrite) 什么是CopyOnWrite容器 CopyOnWrite容器即写时复制的容器.通俗的理解是当我们往一个容器添加元素的时候,不直接往当前容器添加,而是先将当前容器进 ...

  3. openvpn路由配置

    openvpn路由配置 通常openvpn部署好以后,客户端连接VPN后会被配置一些路由,其客户端的路由会被修改为所有的流量都通过VPN来传输.但有时候,我们需要客户端的某些IP走VPN或者本地网关. ...

  4. vscode插件和快捷键

    目前用的挺多的一些编辑器有webstorm,vscode,Atom,HBuilder等等 今天来说说vscode Visual Studio Code (简称 vscode) 是一款免费开源的现代化轻 ...

  5. 交叉熵的数学原理及应用——pytorch中的CrossEntropyLoss()函数

    分类问题中,交叉熵函数是比较常用也是比较基础的损失函数,原来就是了解,但一直搞不懂他是怎么来的?为什么交叉熵能够表征真实样本标签和预测概率之间的差值?趁着这次学习把这些概念系统学习了一下. 首先说起交 ...

  6. 在window系统下安装Sass

    1.Ruby下载 因为Sass依赖于Ruby环境,所以应先在window系统下安装Ruby,Ruby安装包下载链接:http://rubyinstaller.org/downloads/ 2.Ruby ...

  7. Flask最强攻略 - 跟DragonFire学Flask - 第四篇 Flask 中的模板语言 Jinja2 及 render_template 的深度用法

    是时候开始写个前端了,Flask中默认的模板语言是Jinja2 现在我们来一步一步的学习一下 Jinja2 捎带手把 render_template 中留下的疑问解决一下 首先我们要在后端定义几个字符 ...

  8. 【通信】Jave代码中生成url http请求

    /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1& ...

  9. 利用 python requests完成接口文件上传

    最近在准备一个公开课,主题就是利用不同的语言和不同的工具去实现文件的上传和下载. 在利用Jmeter去实现功能的时候,以及利用loadrunner去写脚本的时候,都很顺利,没有任何问题,当我尝试用Py ...

  10. Debian ifconfig 命令找不到

    如何配置让 Debian 非特权用户也可以使用 ifconfig . ifconfig 在 /sbin 目录下,新建一个用户时, Debian 默认从 /etc/skel/ 复制配置文件, /sbin ...