1

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

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

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

使用实体框架,我能够像这样构建 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 查询,我不确定如何为 OrmLight 构建 where 语句。

4

2 回答 2

2

我们最近在 OrmLite ExpressionVisitor 中添加了表达式链 - 从单元测试中复制和粘贴代码:

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"));

注意: Where(x => predicate) 和 .And(x => predicate) 在功能上是相同的。

您还可以建立您的 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);

}

于 2012-12-09T20:24:32.937 回答
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();

}
于 2012-12-08T19:34:24.910 回答