2013-10-03 66 views
2

在对RavenDB进行查询时,是否可以对枚举进行排序或排序?也许通过提供IComparable?RavenDB按枚举排序

我试过了,但它看起来像它的命令,如果枚举是一个字符串,并且它不适用于将枚举存储为整数。

这里有一个简单的例子:

public class Car 
{ 
    public long Id { get; set; } 
    public int NumberOfDoors { get; set; } 
    public int MaxSpeed { get; set; } 
    public Classification Classification { get; set; } 
} 

public enum Classification 
{ 
    Compact, 
    Hatch, 
    Convertible, 
    Muscle 
} 

我想通过分类顺序命令:肌肉,紧凑,哈奇,敞篷车。我想避免重新排列枚举并将枚举存储为整数。

我已经试过这一点,但它似乎不工作:

//My query 
var cars = session.Query<Car>() 
        .OrderBy(c => c.Classification , new ClassificationComparer()) 
        .Skip(offset) 
        .Take(size); 


public class ClassificationComparer: IComparer<Classification> 
{ 
    public int Compare(Classification x, Classification y) 
    { 
     return Order(x).CompareTo(Order(y)); 
    } 

    private int Order(Classification classification) 
    { 

     switch (classification) 
     { 
      case Classification.Compact: 
       return 0; 
      case Classification.Hatch: 
       return 1; 
      case Classification.Convertible: 
       return 2; 
      case Classification.Muscle: 
       return 3; 
      default: 
       return int.MaxValue; 
     } 
    } 
} 

任何帮助表示赞赏。

回答

2

您可能需要使用this answer中提出的解决方案,该解决方案显示如何使用其基础int值在RavenDB中保留枚举。

不过,如果你想保持Classification财产由int值的字符串和订单查询结果,一个可能的解决方案是这样的:

创建映射现有的汽车和广告对应的ClassificationId索引:

public class SortableCarIndex : AbstractIndexCreationTask<Car, SortableCar> 
{ 
    public SortableCarIndex() 
    { 
     Map = cars => 
       from car in cars 
       select 
        new SortableCar 
         { 
          Car = car, 
          ClassificationId = 
           Array.IndexOf(new[]{ 
            "Compact", 
            "Hatch", 
            "Convertible", 
            "Muscle" 
           }, car.Classification) 
         }; 
    } 
} 

public class SortableCar 
{ 
    public Car Car { get; set; } 
    public int ClassificationId { get; set; } 
} 

确保该索引是存在于数据库中,使用的代码folloing行创建DocumentStore后:

IndexCreation.CreateIndexes(typeof(SortableCarIndex).Assembly, documentStore); 

创建索引后,就可以查询它是这样的:

var carsOrderedByClassification = 
     session.Query<SortableCar, SortableCarIndex>() 
       .OrderBy(x => x.ClassificationId) 
       .AsProjection<Car>() 
       .ToList(); 
+0

谢谢你的输入。我得出的结论是,排序只能在简单的类型上完成,所以你的例子是可以使用的 –