ASP.NET MVC - Model.OrderBy Date 无效 [英] ASP.NET MVC - Model.OrderBy Date has no effect

查看:15
本文介绍了ASP.NET MVC - Model.OrderBy Date 无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在按日期对结果进行排序时遇到了一些困难.有什么特别的方法吗?因为我现在正在这样做:

I'm having some difficulties to sort my results by Date. Is there any special method? Because I'm doing this right now:

var db = new DB();
var articles = db.Articles;
var orderedArticles = articles.OrderBy(a => a.Date);
return View(orderedArticles.ToList());

其中日期是日期时间字段.并且对 OrderBy(..)OrderByDescending(..)

Where Date is a datetime field. And there is no effect for OrderBy(..) or OrderByDescending(..)

所以我设法检查发生了什么.

So I managed to check what is happening.

每次我添加新文章时,我只是使用日期而不是时间如果我在同一天有两篇文章,例如:与:

Everytime I add a new Article I'm just using the date on not the time so if I have two articles both for the same day for example: with:

var orderedArticles = db.Articles.OrderByDescending(a => a.Date).ToList();

我会

Id         Title                           Date
10         First Added  Article            16/09/2009 00:00
11         Second Added Article            16/09/2009 00:00
15         Old Article Added Later         15/09/2009 00:00

所以你可以看到它是按日期过滤的,但问题是当我有相同的日期时,排序失去了焦点.所以我所做的是, orderBy 两个不同的上下文,例如首先按 Id 订购,然后按日期订购:

So you can see that is filtering by date, but the thing is when I have the same date the sorting loses the focus. So what I did is, orderBy two different contexts like first order by Id and later order by Date:

var orderedArticles = db.Articles.OrderByDescending(a => a.Id).OrderByDescending(a => a.Date).ToList();

所以在此之后我有以下内容:

So after this I have the following:

Id         Title                           Date
11         Second Added Article            16/09/2009 00:00
10         First Added  Article            16/09/2009 00:00
15         Old Article Added Later         15/09/2009 00:00

我真的不知道这是否是正确的方法,因为主要问题是当你提交一个日期字段时,比如 16/09/2009 它将时间设置为 00:00,这是一个问题这种情况.

I really don't know if this is the right way to do it because the main problem is that when you submit a date field like 16/09/2009 it sets the time to 00:00 and this is a problem on this situation.

推荐答案

这段代码看起来不错.您应该检查 Date 字段中的实际内容,并确保您不例如仅在数据库级别设置 DateTime 对象的日期,这将导致某个日期的所有 DateTime 对象指向 00:00:00因此 LINQ 不知道如何对它们进行排序.

This code looks good. You should check what is really in the Date field and make sure you do not for example only set the Date of the DateTime object on the database level, that would result in all DateTime objects of a certain date to point to 00:00:00 thus the LINQ would not know how to sort them.

这篇关于ASP.NET MVC - Model.OrderBy Date 无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆