SELECT Distinct CarMakes from table using LINQ

Nehemiah Cheburet 21 Reputation points
2021-02-19T06:09:06.84+00:00

I have a table that has CarMake, CarModels and several other columns. I wan to select distinct carmake only.
What I have done:

public IEnumerable<EbimaCarMakesAndModel> GetAll()
{
            var data = (from dbo in context.EbimaCarMakesAndModels where dbo.Listed == "Y" select dbo.CarMake).Distinct().OrderBy(name => name);

            return (IEnumerable<EbimaCarMakesAndModel>)data;
}

but i get an error as:

InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[System.String]' to type 'System.Collections.Generic.IEnumerable`1[motor_backend.Models.EbimaCarMakesAndModel]'.
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,140 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,205 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 111.8K Reputation points
    2021-02-19T06:48:34.257+00:00

    If CarMake to be returned is a string, then the function should be:

    public IEnumerable<string> GetAll()
    {
       return 
            context.EbimaCarMakesAndModels
                 .Where( m => m.Listed == "Y" )
                 .Select( m => m.CarMake )
                 .Distinct( )
                 .OrderBy( n => n );
    }
    

    Give more details if this does not work.


1 additional answer

Sort by: Most helpful
  1. Duane Arnold 3,211 Reputation points
    2021-02-19T07:06:05.137+00:00

    InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1[System.String]' to type 'System.Collections.Generic.IEnumerable1[motor_backend.Models.EbimaCarMakesAndModel]'.

    var data = (from dbo in context.EbimaCarMakesAndModels where dbo.Listed == "Y" select dbo.CarMake).Distinct().OrderBy(name => name)

    What 'data' contains after the query is 'string' data, and it's not a collection of motor_backend.Models.EbimaCarMakesAndModel objects.

    the 'select dbo.CarMake' is maybe just returning 'name' data -- string.

    var data = (from dbo in context.EbimaCarMakesAndModels.where(a => a.Listed == "Y").Distinct(a => a.CarMake).OrderBy(a => a.name)) select dbo).ToList();

    It's going to be something like above using Linq and lambda expressions. You may have to play with the syntax a little bit.

    https://www.c-sharpcorner.com/article/writing-complex-queries-using-linq-and-lambda/