根据基于消息的请求构建where过滤器

时间:2012-12-08 13:57:35

标签: c# servicestack ormlite-servicestack

我有一个小的请求对象来过滤。

public class BufferFlatViewFilter
{
    public bool? Active { get; set; }
    public int? CustomerId { get; set; }
    public int? TypeId { get; set; }
}

我需要为db请求建立where过滤器。

使用Entity框架,我能够像这样构建Where语句。

public List<BufferFlatView> GetBufferFlatView(BufferFlatViewFilter filter)
{
    var data = db.qryCampaignOverView
        .AsQueryable();

    if (filter.TypeId.HasValue)
        data = data.Where(x => x.TypeId == filter.TypeId.Value);

    if (filter.CustomerId.HasValue)
        data = data.Where(x => x.CustomerId == filter.CustomerId);

    if (filter.Active)
        data = data.Where(x => x.Active == filter.Active);

    return data.ToList();
}

我不确定如何为OrmLight构建where语句,因为Entity框架查询是延迟加载的,而不是OrmLight查询。

2 个答案:

答案 0 :(得分:2)

我们最近在OrmLite ExpressionVisitor中添加了表达式链接 - 代码副本&amp;粘贴在单元测试中:

var visitor = dbConnection.CreateExpression<Person>();
visitor.Where(x => x.FirstName.StartsWith("Jim")).And(x => x.LastName.StartsWith("Hen"));
var results = db.Select<Person>(visitor);
Assert.AreEqual(1,results.Count);

visitor.Where(x => x.Age < 30).Or(x => x.Age > 45);
results = db.Select<Person>(visitor);
Assert.AreEqual(5, results.Count);
Assert.IsFalse(results.Any(x => x.FirstName == "Elvis"));

注意:其中(x =&gt;谓词)和.And(x =&gt;谓词)在功能上相同。

您还可以建立Order By表达式

visitor.OrderBy(x => x.Name).ThenByDescending(x => x.Age);

所以你的代码变成了

public List<BufferFlatView> GetBufferFlatView(BufferFlatViewFilter filter)
{
    //assumes IDbConnection instance injected by IOC
    var ev = dbConnection.CreateExpression<Campaign>();

    if (filter.TypeId.HasValue)
        ev.Where(x => x.TypeId == filter.TypeId.Value);

    if (filter.CustomerId.HasValue)
        ev.Where(x => x.CustomerId == filter.CustomerId);

    if (filter.Active)
        ev.Where(x => x.Active == filter.Active);

    return dbConnection.Select<Campaign>(ev);

}

答案 1 :(得分:0)

你可以做这样的事情。

public class Poco
    {
        public int TypeId { get; set; }
        public int CustomerId { get; set; }
        public bool Active { get; set; }
    }

public class Filter<T>
{
    private List<Func<T, bool>> filters = new List<Func<T, bool>>();

    public void AddFilter(Func<T, bool> filter)
    {
        this.filters.Add(filter);
    }
    public bool PredicateFilter(T item)
    {
        return filters.All(x => x(item));
    }
}

static void Main(string[] args)
{

    var list = new List<Poco>() { new Poco { Active = true, CustomerId = 1, TypeId = 1 } };

    var filter = new Filter<Poco>();
    filter.AddFilter(x => x.Active == false);
    filter.AddFilter(x => x.CustomerId == 1);
    filter.AddFilter(x => x.TypeId == 1);

    var item = list.Where(x => filter.PredicateFilter(x));


    Console.Read();

}