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

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

问题描述

我很难按日期对我的结果进行排序.有什么特殊的方法吗? 因为我现在正在这样做:

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

所以您可以看到它按日期进行过滤,但问题是当我具有相同的日期时,排序就失去了重点. 所以我要做的是,通过两个不同的上下文对订单进行排序,例如按ID排序的第一个顺序,然后按Date排序的后一个顺序:

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

我真的不知道这是否是正确的方法,因为主要问题是,当您提交日期字段(如2009年9月9日)时,它将时间设置为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.

推荐答案

这段代码看起来不错.您应该检查日期"字段中的内容,并确保例如仅在数据库级别上不设置DateTime对象的Date,这将导致某个日期的所有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日期无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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