过滤"基本查询"结果略有不同

时间:2014-04-26 22:51:09

标签: c# sql-server entity-framework

我正在尝试使用Entity Framework查询数据库,我需要在同一组表上进行几个稍微不同的查询。我需要添加一大堆导航属性,我认为我应该能够定义“基本查询”(即具有所有导航属性的那个),然后根据需要进一步过滤并执行查询

某些代码可能有助于进一步解释。这就是我所谓的“基本查询”

private static IEnumerable<HelpdeskTicket> GetAll()
{
    IEnumerable<HelpdeskTicket> Tickets;

    using (ItManagement_Entities db = new ItManagement_Entities())
    {
        Tickets = db.HelpdeskTickets.Include("CreatedByPerson")
                                    .Include("HelpdeskCategory")
                                    .Include("HelpdeskPriority")
                                    .Include("HelpdeskStatus");
    }

    return Tickets;
}

例如,我需要执行的一些查询是打开的门票,最近关闭的门票,我的门票,yada yada yada。

我的想法是使用类似于以下的方法来完成我需要的过滤位,而无需再次定义所有.Include()

public static List<HelpdeskTicketModel> GetAllTickets()
{
    List<HelpdeskTicketModel> Tickets = new List<HelpdeskTicketModel>();

    GetAll().OrderByDescending(t => t.TicketId)
            .ToList()
            .ForEach(t => Tickets.Add(HelpdeskTicketModel.Map(t)));

    return Tickets;
}

public static List<HelpdeskTicketModel> GetRecentlyClosedTickets()
{
    List<HelpdeskTicketModel> Tickets = new List<HelpdeskTicketModel>();

    GetAll().Where(t => t.HelpdeskStatus.IsClosedStatus)
            .OrderByDescending(t => t.ClosedTime)
            .ToList()
            .ForEach(t => Tickets.Add(HelpdeskTicketModel.Map(t)));

    return Tickets;
}

//And so on...

当我尝试这个时,我得到一个System.InvalidOperationException异常,抱怨The operation cannot be completed because the DbContext has been disposed,这是有道理的,因为我的查询 在不同的上下文中,{{1}方法。

问题是,我该如何做我想做的事?

1 个答案:

答案 0 :(得分:0)

您可以尝试类似于Template Method pattern的内容,其中每个特定方法调用一些基本的私有方法来执行常见工作,然后每个方法都会添加查询的特定位。这样的事情可能会成为一个起点:

// Here you define common parts applicable to all methods, or at least shared among some of them
private static IQueryable<HelpdeskTicket> BuildBaseQuery(this IQueryable<HelpdeskTicket> query)
{
    return query.Include("CreatedByPerson")
                .Include("HelpdeskCategory")
                .Include("HelpdeskPriority")
                .Include("HelpdeskStatus");
}

// Here are the particular methods, they create a query, call helper methods for the common bits and add their specifics
public static List<HelpdeskTicketModel> GetAllTickets()
{
    List<HelpdeskTicketModel> Tickets = new List<HelpdeskTicketModel>();

    using (ItManagement_Entities db = new ItManagement_Entities())
    {
        Tickets = db.HelpdeskTickets.BuildBaseQuery()
                                    .OrderByDescending(t => t.TicketId)
                                    .ToList()
                                    .ForEach(t => Tickets.Add(HelpdeskTicketModel.Map(t)));
    }

    return Tickets;
}