如何在这种特定情况下执行有效的订单?

时间:2015-10-13 19:35:34

标签: c# asp.net-mvc entity-framework linq

所以我写这个查询,它运行正常:

(from schools in context.Schools
                           // some kind of fancy joins
                           select new SomeLocalDTO()
                           {
                               SchoolId = schools.SchoolId,
                               FancySchoolName = schools.SchoolId + "**** -*****  " + schools.SchoolName

                            })
                        .AsQueryable();
/// I have some fancy code here which will aslso take care of take/skip.
// I WANT TO DO ORDER BY HERE, after the skip and take

问题是我想在完成所有花哨的代码/跳过之后订购。但问题是我在select语句中没有学校名称,而是我拥有的是FancySchoolName。我该怎么办?

注1:我无法更改SomeLocalDTO,以便在选择中包含schoolname 注2:根据我的业务要求,我不在乎ABCDEF的结果是否得到ABC或FED。 注3:我知道这是一个奇怪的请求,只是一个奇怪的业务需求。

2 个答案:

答案 0 :(得分:3)

您可以创建一个SomeLocalDTO的子类,其中包括SchoolName,让您的LINQ创建这些对象,然后在返回调用者时向下转发到SomeLocalDTO

更新:

基于你所说的一切,这就是我仍然在解释你想要的东西......在初始查询之后的OrderBy / Take / Skip,但仍按SchoolName排序:

public class MyDTO: SomeLocalDTO
{
   public string SchoolName {get;set;}
}

var result = (from schools in context.Schools
                           // some kind of fancy joins
                           select new MyDTO()
                           {
                               SchoolId = schools.SchoolId,
                               FancySchoolName = schools.SchoolId + "**** -*****  " + schools.SchoolName,
                               SchoolName = schools.SchoolName    
                            });

return result.OrderBy(s => s.SchoolName)
             .Skip(...)
             .Take(...)
             .Cast<SomeLocalDTO>();

答案 1 :(得分:2)

这是一个非常奇怪的订单请求,请采取/跳过,然后是不同的订单,但是:

var something=(from schools in context.Schools
  // some kind of fancy joins
  orderby schools.Name
  select schools);
// take/skip
var result=something.OrderBy(...).Select(schools=>
  new SomeLocalDTO()
  {
    SchoolId = schools.SchoolId,
    FancySchoolName = schools.SchoolId + "**** -*****  " + schools.SchoolName
  });

基于你的困惑,我怀疑这就是你想要的:

var something=context.Schools
  .OrderBy(schools=>schools.SchoolName)
  .Skip(...)
  .Take(...)
  .Select(schools=>
    new SomeLocalDTO()
    {
      SchoolId = schools.SchoolId,
      FancySchoolName = schools.SchoolId + "**** -*****  " + schools.SchoolName
    });