实体框架分离选择,计数和过滤

时间:2014-08-16 05:51:36

标签: c# entity-framework

我想从每个操作中分离过滤,计数和选择操作,但是我收到错误

  

实体或复杂类型'父母'不能在LINQ to Entities查询中构造。

来自GetData函数。

我知道这个问题,但我无法解决。分离这些复杂查询的正确架构是什么?

string string name="Any Name";

int childId = 4;
int page = 2, maxDispItem = 10;

public IQueryable<Parent> GetFilteredData()
{   
    GetData().Where(o=>o.Name==name).SelectMany(o=>o.Children).
            Where(o=>o.ID>childId).Select(o=>o.Parent).AsQueryable();
}

public IQueryable<Parent> GetData()
{
    return context.Set<Parent>.AsNoTracking().Select(o => new { o.ID,o.Name, 
          Childs = o.Children.Select(t => new { t.ID }) }).
        Select(o => new Parent { ID = o.ID, Name = o.Name, 
          Children = o.Childs.Select(t => new Child { ID = o.ID }).ToList()}).
       AsQueryable();        
}

public int GetDataCount()
{
    return GetFilteredData().SelectMany(o=>o.Children).Count();
}

public List<Parent> GetModelData()
{
    return GetFilteredData().OrderBy(o => o.ID).
           Skip(maxDispItem * (page -1)).Take(maxDispItem).ToList();
}

1 个答案:

答案 0 :(得分:0)

首先,您需要了解它的含义以及IQueryable<>IOrderedQueryable<>IEnumerable<>

之间的区别

以下是我如何区分逻辑:

public int GetCount(IQueryable<Parent> query)
{
    return query.Count();
}

public IQueryable<Parent> GetQuery(string name, int? childId)
{
     var query = context.Set<Parent>().AsQueryable();

     if (!string.IsNullOrEmpty(name))
     {
          query = query.Where(x => x.Name == name);
     }

     if (childId.HasValue)
     {
         query = query.Where(x => x.Children.Any(y => y.Id == childId.Value));
     }

     return query;
}

public IOrderedQueryable<Parent> GetOrderedQuery(IQueryable<Parent> query)
{
      return query.OrderBy(x => x.Id);
}

public IEnumerable<Parent> GetPageData(IOrderedQueryable<Parent> query, int page, int pageSize)
{
      return query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
}

public void Example()
{
     // filter
     var query = GetQuery("Test", 4);

     // total count on filtered query
     var count = GetCount(query);

     // order
     var orderedQuery = GetOrderedQuery(query);

     // paginate and execute query
     var pagedData = GetPageData(orderedQuery, page: 1, pageSize: 2);
 }

What is the difference between IQueryable<T> and IEnumerable<T>?