如下代码,我实现了单条件查询数据的方法的封装,可以动态查询。但是我现在想继续扩展,实现多条件查询,请问这个方法该如何修改?
/// <summary>
/// Linq Where 语句Func参数查询
/// </summary>
/// <typeparam name="TSource">查询对象</typeparam>
/// <param name="property">查询属性</param>
/// <param name="value">查询属性对应值</param>
/// <returns></returns>
private Func<TSource, bool> SimpleComparison<TSource>(string property, object value)
{
var type = typeof(TSource);
var pe = Expression.Parameter(type, "p");
var propertyReference = Expression.Property(pe, property);
var constantReference = Expression.Constant(value);
return Expression.Lambda<Func<TSource, bool>>
(Expression.Equal(propertyReference, constantReference),
new[] { pe }).Compile();
}
/// <summary>
/// 删除数据
/// </summary>
/// <typeparam name="T">删除的数据类型,与数据库字段类型需要相对应</typeparam>
/// <param name="field">字段属性</param>
/// <param name="id">根据此字段属性的值删除</param>
public virtual void Delete<T>(string field, T id)
{
var entity = dbSet.Cast<TEntity>().Where(SimpleComparison<TEntity>(field, id)).FirstOrDefault();
dbSet.Cast<TEntity>().Attach(entity);//将 通过主键 实例化的实体类附加到EF中
dbSet.Cast<TEntity>().Remove(entity);//删除
Commit();
}
/// <summary>
/// Linq Where 语句Func参数查询
/// </summary>
/// <typeparam name="TSource">查询对象</typeparam>
/// <param name="property">查询属性</param>
/// <param name="value">查询属性对应值</param>
/// <returns></returns>
private Func<TSource, bool> SimpleComparison<TSource>(string property, object value)
{
var type = typeof(TSource);
var pe = Expression.Parameter(type, "p");
var propertyReference = Expression.Property(pe, property);
var constantReference = Expression.Constant(value);
return Expression.Lambda<Func<TSource, bool>>
(Expression.Equal(propertyReference, constantReference),
new[] { pe }).Compile();
}
/// <summary>
/// 删除数据
/// </summary>
/// <typeparam name="T">删除的数据类型,与数据库字段类型需要相对应</typeparam>
/// <param name="field">字段属性</param>
/// <param name="id">根据此字段属性的值删除</param>
public virtual void Delete<T>(string field, T id)
{
var entity = dbSet.Cast<TEntity>().Where(SimpleComparison<TEntity>(field, id)).FirstOrDefault();
dbSet.Cast<TEntity>().Attach(entity);//将 通过主键 实例化的实体类附加到EF中
dbSet.Cast<TEntity>().Remove(entity);//删除
Commit();
}