C# OrderByDescending在EF中不';行不通

C# OrderByDescending在EF中不';行不通,c#,entity-framework,C#,Entity Framework,嗨,伙计们,我有一个这样的模型: public partial class Path { public Path() { this.Sensors = new HashSet<Sensor>(); } public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } publi

嗨,伙计们,我有一个这样的模型:

public partial class Path
{
    public Path()
    {
        this.Sensors = new HashSet<Sensor>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string StartStationId { get; set; }
    public string EndStationId { get; set; }
    public int LineId { get; set; }
    public string Order { get; set; }

    public virtual Line Line { get; set; }
    public virtual ICollection<Sensor> Sensors { get; set; }
}
公共部分类路径
{
公共路径()
{
this.Sensors=new HashSet();
}
公共int Id{get;set;}
公共字符串名称{get;set;}
公共字符串说明{get;set;}
公共字符串StartStationId{get;set;}
公共字符串EndStationId{get;set;}
public int LineId{get;set;}
公共字符串顺序{get;set;}
公共虚拟行{get;set;}
公共虚拟ICollection传感器{get;set;}
}
我尝试按以下代码对该实体的列表进行排序:

   List<Path> lstPath = _dbcontext.Paths.Where(i=>i.LineId==lineNumber).OrderByDescending(i => i.Order).ToList();
List lstPath=\u dbcontext.path.Where(i=>i.LineId==lineNumber).OrderByDescending(i=>i.Order.ToList();
顺便说一下,我将其更改为以下代码:

List<Path> lstPath = _dbcontext.Paths.Where(i=>i.LineId==lineNumber).ToList();
       lstPath = lstPath.OrderByDescending(i => i.Order).ToList();
List lstPath=\u dbcontext.path.Where(i=>i.LineId==lineNumber.ToList();
lstPath=lstPath.OrderByDescending(i=>i.Order.ToList();
但它不会根据订单列对列表进行排序!!!为什么?


最好的祝愿

因为您将数字存储为字符串,所以很可能是按字母顺序而不是数字顺序排序,例如:

1
10
11
2
3
...
正确的做法是更改模型,使
Order
为数字类型,因为:

  • 将数字数据存储为字符串本身就是一种糟糕的设计
  • 您将拥有一个与数据源实际匹配的模型
  • 您可以在对数据排序时排除猜测(“顺序”不是一个神秘值)

  • 编辑:我删除了以前的一个建议,将
    Order
    属性转换为
    OrderByDescending
    lambda表达式中的
    整数,但实体框架无法对数据库执行该操作,因此需要对内存中的数据进行排序。

    排序是什么样的?你看到的是什么顺序,你期望的是什么?解释什么是“不起作用”的意思。具体来说,哪里出了问题?您告诉它做一些完全不同的事情,即对内存中的列表进行排序,而不是要求数据库对数据进行排序,这两者可以以不同的方式定义“排序”,但它们都会“工作”。@EA那么这就是您的问题。将数字存储为数字,不要将其存储为字符串,您的问题将全部消失。@EA:检查您的结果是否按字母顺序排列(例如1、10、100、2、3、31、314等)。如果他们愿意,请尝试我的建议。这要求排序在应用程序的内存中进行,而不是在DB端进行,增加了不必要的开销,而且在概念上是错误的。将整数数据存储为字符串本质上是一个坏主意,应该通过将其存储为整数来修复。执行后,我遇到了以下错误:LINQ to Entities无法识别方法“Int32 ToInt32(System.string)”方法,并且该方法无法转换为存储expression@EA只能在内存中使用
    Convert.ToInt32
    ,也就是说,在调用
    ToList
    AsEnumerable
    @p.s.w.g是的,我需要对MemoryTanks中的值进行排序以获得建议后,我已更新了我的答案。它在@Cory起作用,执行:D是我的错