实体框架按Enum值按字母顺序排序 [英] Entity Framework sort by Enum value alphabetically
问题描述
我有一个名为 Comment
的实体,该实体具有类型为 CommentType
的 enum
属性:
I have an entity called Comment
, which has an enum
property of type CommentType
:
public class Comment
{
public virtual Guid Id { get; private set; }
public virtual CommentType CommentType { get; set; }
// other prop removed for simplicity
}
public enum CommentType
{
Comment,
Correction,
Improvement,
BugFix,
NewFeauture,
Other
}
我需要通过 CommentType
枚举的按字母顺序
值从数据库中选择注释,例如
I need to select the comments from database by the alphabetically
value of the CommentType
enum, something like
_db.Comments.OrderBy(p => p.CommentType)
但是,Enum值被视为整数,并且排序不能按字母顺序正确地工作.
However, the Enum values are treated as integers, and the sort will not work alphabetically correctly.
是否可以将某些属性/元数据添加到Enum值中,以使它们按字母顺序正确排序?
Is there any way to add some attributes / metadata to the Enum values to make them sort correctly alphabetically?
一种解决方案是将整数值分配给枚举值,但是我已经有很多数据库记录需要更新.而且此解决方案不适用于新添加的枚举值.
One solution will be to assign the integer value to enum values, but i already have many database records that will need to be updated. And this solution is not good for new added enum values.
public enum CommentType
{
Comment = 2,
Correction = 3,
Improvement = 4,
BugFix = 1,
NewFeauture = 5,
Other = 6
}
推荐答案
当前在数据库级别尚不知道您的枚举名称,因此我认为您有两种选择.
Currently your enum name is not known at database level so in my opinion you have two options.
-
在服务器端使用值:
Use value on server side:
_db.Comments.ToList().OrderBy(p => p.CommentType.ToString())
在数据库端添加值:您应该创建将包含注释类型名称的表.然后,您可以在注释和commentTypeNames之间创建外键,并使用简单的选择:
Add value on database side: You should create table that will contain comment type names. And then you can create foreign key between comments and commentTypeNames and use simple select:
_db.Comments.OrderBy(c => c.CommentTypeNames.Name)
或者只是加入:
_db.Comments
.Join(
_db.CommentTypeNames,
c => c.CommentType,
ctn => ctn.CommentType,
(c, ctn) => new { Comment = c, CommentName = ctn })
.OrderBy(g => g.CommentName.Name)
.Select(g => g.Comment);
也有计算列.我从来没有用过,所以我没有经验.也许您可以添加将由数据库上的CASE语句解析为字符串的列.但是,我不确定这将如何影响性能/可维护性.有关更多信息,您可以检查出于性能方面的考虑,我建议您采用选项2,最好在数据库中执行此类操作.
For performance reasons I would advise to take option 2, it's better to do such things in database.
I assume that you are using code first so maybe this post will be helpful for you: EF5 Code First Enums and Lookup Tables
这篇关于实体框架按Enum值按字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!