【问题标题】:How to select a row(object) based on max of a field Entity Framework 4.1如何根据字段实体框架 4.1 的最大值选择行(对象)
【发布时间】:2012-02-29 10:30:16
【问题描述】:

我试图根据RollNumber 的最大值获取一行(对象),这是一个很长的Datatype field。我希望它返回一个空对象,以防万一没有,所以我使用了SingleorDefault。但似乎我的查询全错了(这里的 linq 正在进行中)。 这是查询:

SchoolContextExpress db = new SchoolContextExpress();
        Profile profile = db.Profiles.Where(p => p.RollNumber == db.Profiles.Max(r=>r.RollNumber)).SingleOrDefault();

感谢您阅读本文。

【问题讨论】:

  • 我觉得不错。有什么问题?
  • 嗯,在这里工作正常!你有错误吗?
  • 包含多个元素
  • 你有重复的卷号吗?
  • 啊哈!有空的,索引允许空行。他们留空的原因是因为在我的业务逻辑中我想在发布卷号之前验证注册。因此,在注册时,所有内容都已保存,但 rollnumber 为空(在此长上下文中为零)。我该如何解决这个问题?

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


【解决方案1】:

使用空 RollNumber...

Profile profile = db.Profiles.Where(p => p.RollNumber !=0 &&  p.RollNumber == db.Profiles.Max(r=>r.RollNumber)).SingleOrDefault();

或者你可以考虑...

Profile profile = db.Profiles.Where(p => p.RollNumber == db.Profiles.Where(p1 => p1.RollNumber != 0).Max(r=>r.RollNumber)).SingleOrDefault();

【讨论】:

  • 我想我会做与零不同的事情,因为 RollNumber 很长。可以吗?
【解决方案2】:

除了第一个答案之外的另一种方法:

Profile profile = db.Profiles.OrderByDescending(p => p.RollNumber).FirstOrDefault();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多