Skip to content

Linq generation error (OrderBy/Skip/Take?) #6257

Closed

Description

@AlexFsmn

Hello,
Im trying to port an old ASP.NET WebAPI project to .NET Core. (The code works with EF 6)
While doing so I encountered an error with one of my Linq-queries.
Im not really sure what SQL is generated from the query but it seems to be wrong since the error doesn't make any sense to me.

Models

public class Node
{
    public Node()
    {
        NodeRecords = new List<NodeRecord>();
    }
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Name { get; set; }
    public virtual List<NodeRecord> NodeRecords { get; set; }
}

public class NodeRecord
{
    [Key]
    public int NodeRecordId { get; set; }
    [Column("Node_Name")]
    [ForeignKey("Node_Name")]
    public string NodeName { get; set; }
    public int Change { get; set; }
}

 public class HighNode
{
    public string Name { get; set; }
    public int Change { get; set; }
}

Code

private List<HighNode> GetHighNodeDaysAgo(int days)
{
    List<HighNode> selection = new List<HighNode>();
    using (GameStatsDb db = new GameStatsDb())
    {
        selection = db.Nodes.Include(x => x.NodeRecords)
        .Select(s => new HighNode()
        {
            Name = s.Name,
            Change = s.NodeRecords.OrderByDescending(o => o.NodeRecordId).Skip(days).FirstOrDefault().Change
        }).OrderByDescending(t => t.Change).Take(100).ToList();
    }
    return selection;
}

Error Information:

An exception of type 'System.InvalidCastException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code

Additional information: Unable to cast object of type 'System.Int32' to type 'GameDbModels.NodeRecord'.

StackTrace

 at lambda_method(Closure , ValueBuffer )
   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at GameStatsServiceCrossPlatform.Controllers.NodeController.GetHighNodeDaysAgo(Int32 days) in ~\Controllers\NodeController.cs:line 82
   at GameStatsServiceCrossPlatform.Controllers.NodeController.GetTodaysHighNodes() in ~\Controllers\NodeController.cs:line 33
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionFilterAsync>d__28.MoveNext()

Further technical details
Visual Studio version and tool:
Running Microsoft .NET Core Tools (Preview 2) in VS 2015 update 3
OS:
Windows 10
Framework versions:
"Microsoft.EntityFrameworkCore": "1.0.0",
"Microsoft.EntityFrameworkCore.Relational": "1.0.0",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",

Any idea what could be the issue?
I haven't seen that Take & Skip aren't supported yet and I have seen examples containing orderby.

Activity

  1. added this to the 1.1.0 milestone on Aug 8, 2016
  2. nourselim0 commented on Aug 12, 2016

    @nourselim0

    I've faced this issue too, it seems to happen when doing Take or First on navigational properties.
    I kept trying workarounds (changing the order of things in my query) and so on, and I wasn't able to pinpoint when it happens and when it doesn't happen. But even when this but didn't happen, the Take(1) or First didn't make it to the SQL Query and I got warning that EF failed to translate that part of the query.
    After fighting this for hours I settled down for splitting the query into two parts (with the second part happening for every entry returned from the first part!), but I really hope this gets fixed soon!

  3. maumar commented on Oct 5, 2016

    @maumar
    Contributor

    Need to verify if this already fixed.

  4. maumar commented on Oct 6, 2016

    @maumar
    Contributor

    This is indeed fixed now. We generate the following query:

    SELECT TOP(@__p_1) [x].[Name], (
        SELECT [o0].[Change]
        FROM [NodeRecords] AS [o0]
        WHERE [x].[Name] = [o0].[Node_Name]
        ORDER BY [o0].[NodeRecordId] DESC
        OFFSET @__days_0 ROWS FETCH NEXT 1 ROWS ONLY
    )
    FROM [Nodes] AS [x]
    ORDER BY (
        SELECT [o].[Change]
        FROM [NodeRecords] AS [o]
        WHERE [x].[Name] = [o].[Node_Name]
        ORDER BY [o].[NodeRecordId] DESC
        OFFSET @__days_0 ROWS FETCH NEXT 1 ROWS ONLY
    ) DESC
  5. smitpatel commented on Oct 6, 2016

    @smitpatel
    Contributor

    As enhancement we should also alias the subquery.

  6. modified the milestones: , 1.1.0 on Oct 15, 2022
  7. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions