简体   繁体   中英

Entity Framework orderby doesnt order query result

var comments =  (from p in _ctx.CommentRottas
                                .Where(s => s.Rotta_Id == Id && s.Status == 1)
                                .Include(s => s.Client)                              
                            orderby p.Date descending
                            select new CommentDTO
                                {
                                    CommentId = p.Id,
                                    Rotta = new RottaDTO
                                    {
                                        RottaId = p.Rotta_Id,
                                        RottaDate = p.SU_ROUTES.Date,
                                        ClientId = p.SU_ROUTES.ClientId,
                                        COMMENTS_NUM = p.SU_ROUTES.COMMENTS_NUM,
                                        LIKES_NUM = p.SU_ROUTES.LIKES_NUM,
                                    },
                                    Client = new ClientDTO
                                    {
                                        Id = p.Client_Id,
                                        UserName = p.Client.UserName,
                                        Profile_Image = p.Client.Profile_Image,
                                    },
                                    CommentDate = p.Date,
                                    Comment = p.comment,
                                }
                            )
                            .ToList();

            return comments;

Hi guys. I am trying to order comments in descending order by their date. But whatever I tried it does not order. I have similar query to this one and it works. But this one does not. I also tried using OrderByDescending(m => m.CommentDate) but still it does not order query. Do I make some mistake that I do not see or it's some entity framework issue ?

EDIT: Added DB Values

Id RID Comment UID DATE

107 680 test 27 2017-08-24 10:49:41.583 1

108 680 gdfg 27 2017-08-24 10:50:06.630 1

109 681 Khgs gdlkdg 18 2017-08-24 12:08:01.793 1

110 680 ttt 27 2017-08-24 13:24:52.407 1

111 684 dasdasd 27 2017-08-24 13:32:22.997 1

112 680 fdsfs 27 2017-08-24 13:59:24.317 1

113 684 OK 27 2017-08-25 07:35:43.627 1

114 684 Ghfgjn 20 2017-08-25 13:43:15.020 1

Result From Query For RID 684:

[
    {
        "CommentId": 111,
        "CommentDate": "2017-08-24T13:32:22.997",
        "Comment": "dasdasd",
        "Client": {
            "Id": 27,
            "UserName": "Test",
            "Profile_Image": "https://rota2.blob.core.windows.net/profile-images/profile.png"
        },
        "Station": null,
        "Rotta": {
            "RottaId": 684,
            "RottaDate": "2017-08-24T13:30:40.51",
            "COMMENTS_NUM": 3,
            "LIKES_NUM": 2,
            "Completed": 0,
            "STATUS": 0,
            "Is_Started": null,
            "ClientId": 19,
            "Stations": null,
            "Client": null
        },
        "Media": null
    },
    {
        "CommentId": 114,
        "CommentDate": "2017-08-25T13:43:15.02",
        "Comment": "Ghfgjn",
        "Client": {
            "Id": 20,
            "UserName": "Besart2",
            "Profile_Image": "https://rota2.blob.core.windows.net/profile-images/Date-2017-08-28T08-06-21-User-20.jpg"
        },
        "Station": null,
        "Rotta": {
            "RottaId": 684,
            "RottaDate": "2017-08-24T13:30:40.51",
            "COMMENTS_NUM": 3,
            "LIKES_NUM": 2,
            "Completed": 0,
            "STATUS": 0,
            "Is_Started": null,
            "ClientId": 19,
            "Stations": null,
            "Client": null
        },
        "Media": null
    },
    {
        "CommentId": 113,
        "CommentDate": "2017-08-25T07:35:43.627",
        "Comment": "OK",
        "Client": {
            "Id": 27,
            "UserName": "Test",
            "Profile_Image": "https://rota2.blob.core.windows.net/profile-images/profile.png"
        },
        "Station": null,
        "Rotta": {
            "RottaId": 684,
            "RottaDate": "2017-08-24T13:30:40.51",
            "COMMENTS_NUM": 3,
            "LIKES_NUM": 2,
            "Completed": 0,
            "STATUS": 0,
            "Is_Started": null,
            "ClientId": 19,
            "Stations": null,
            "Client": null
        },
        "Media": null
    }
]




GO

/****** Object:  Table [dbo].[CommentRottas]    Script Date: 8/28/2017 7:14:59 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[CommentRottas](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [Rotta_Id] [bigint] NOT NULL,
    [comment] [nvarchar](500) NULL,
    [Client_Id] [int] NOT NULL,
    [Date] [datetime] NOT NULL,
    [Status] [int] NOT NULL,
 CONSTRAINT [PK_dbo.CommentRottas] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
GO

ALTER TABLE [dbo].[CommentRottas]  WITH CHECK ADD  CONSTRAINT [FK_dbo.CommentRottas_dbo.SU_ROUTES_Rotta_Id] FOREIGN KEY([Rotta_Id])
REFERENCES [dbo].[SU_ROUTES] ([ROUTE_ID])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[CommentRottas] CHECK CONSTRAINT [FK_dbo.CommentRottas_dbo.SU_ROUTES_Rotta_Id]
GO

I finally solved problem. I dont know what caused problem but returning object instead of DTO solved problem. This is my solution.

   public ICollection<Object> GetRouteComments(long Id)
    {
        /*
        var result = await _ctx.CommentRottas
                        .Where(s => s.Rotta_Id == Id)
                        .Include(s => s.Client)
                        .Where(s => s.Status == 1)
                        .OrderByDescending(p => p.Date)
                        .ToListAsync();
        */
        var comments = (from p in _ctx.CommentRottas
                           .Where(s => s.Rotta_Id == Id && s.Status == 1)
                           .Include(s => s.Client)
                        orderby p.Date descending
                        select new CommentDTO
                        {
                            CommentId = p.Id,
                            Rotta = new RottaDTO
                            {
                                RottaId = p.Rotta_Id,
                                RottaDate = p.SU_ROUTES.Date,
                                ClientId = p.SU_ROUTES.ClientId,
                                COMMENTS_NUM = p.SU_ROUTES.COMMENTS_NUM,
                                LIKES_NUM = p.SU_ROUTES.LIKES_NUM,
                            },
                            Client = new ClientDTO
                            {
                                Id = p.Client_Id,
                                UserName = p.Client.UserName,
                                Profile_Image = p.Client.Profile_Image,
                            },
                            CommentDate = p.Date,
                            Comment = p.comment,
                        }
                        )
                        .ToList().Cast<Object>().ToList();

        return comments;

您是否尝试过在选择之后而不是之前拥有.OrderBy

如果可以为空,请尝试通过p.Date.GetDefaultOrValue()命令

I Found Solution, But i am not sure why it works.

 public ICollection<Object> GetRouteComments(long Id)
    {
        /*
        var result = await _ctx.CommentRottas
                        .Where(s => s.Rotta_Id == Id)
                        .Include(s => s.Client)
                        .Where(s => s.Status == 1)
                        .OrderByDescending(p => p.Date)
                        .ToListAsync();
        */
        var comments = (from p in _ctx.CommentRottas
                           .Where(s => s.Rotta_Id == Id && s.Status == 1)
                           .Include(s => s.Client)
                        orderby p.Date descending
                        select new CommentDTO
                        {
                            CommentId = p.Id,
                            Rotta = new RottaDTO
                            {
                                RottaId = p.Rotta_Id,
                                RottaDate = p.SU_ROUTES.Date,
                                ClientId = p.SU_ROUTES.ClientId,
                                COMMENTS_NUM = p.SU_ROUTES.COMMENTS_NUM,
                                LIKES_NUM = p.SU_ROUTES.LIKES_NUM,
                            },
                            Client = new ClientDTO
                            {
                                Id = p.Client_Id,
                                UserName = p.Client.UserName,
                                Profile_Image = p.Client.Profile_Image,
                            },
                            CommentDate = p.Date,
                            Comment = p.comment,
                        }
                        )
                        .ToList().Cast<Object>().ToList();

        return comments;

It is a waste of computing time to convert it to a List twice. Besides don't ise Include if you are only using certain parts of the Include result. Entity Framework will know which columns to query.

Having said that. I think your problem is because of the mixing of method syntax and query syntax. Maybe putting some extra parentheses would help.

I've translated your query into method syntax, and used your input. The output is as expected.

int Id = 684;
var result = myDbContext.CommentRottas
    .Where(comment => comment.Id == Id && comment.Status == 1)
    .OrderByDescending(comment => comment.Date)
    .Select(comment => new CommentDTO()
    {
        CommentId = comment.Id,
        Rotta = new RottaDTO
        {
            RottaId = comment.Rotta_Id,
            // not tested all properties
        },
        Client = new ClientDTO()
        {
            Id = comment.Client_Id,
            // not tested all properties  
        },
        CommentDate = comment.Date,
        Comment = comment.Comment,
    })
    .ToList();

This works and gives the expected order. So my advise would be to stick to one syntax: method or query. If you use query syntax, be use parentheses.

Finally: consider not to return the list, but the IEnumerable. If your caller only wants the first element, or the first few, It would be a wast to query everything. Let your caller decide if he wants to add other functions to your IEnumerable before enumerating over it (or put it in a list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM