I have a table that has several columns including CarMake, CarModel, CarModelLoading etc. I want to select distinct CarMake and return them as list. I have tried the following:
public IEnumerable<EbimaCarMakesAndModel> GetAll()
{
//var list<ebima>
return (IEnumerable<EbimaCarMakesAndModel>)context.EbimaCarMakesAndModels.Select(l => new { l.CarMake }).Distinct().ToList();
//var data = (from dbo in context.EbimaCarMakesAndModels where dbo.Listed == "Y" select dbo.CarMake).Distinct().OrderBy(name => name).ToList();
//return (IEnumerable<EbimaCarMakesAndModel>)data;
}
but whenever run the app, I get the error:
An unhandled exception occurred while processing the request. InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List
1[<>f__AnonymousType31
1[System.String]]' to type 'System.Collections.Generic.IEnumerable`1[motor_backend.Models.EbimaCarMakesAndModel]'. I have also tried the following but to no avail:
public IEnumerable<EbimaCarMakesAndModel> GetAll()
{
var res = context.EbimaCarMakesAndModels.GroupBy(x => new { x.CarMake }).
Select(x => x.FirstOrDefault()).Where(v => v.Listed == "Y").ToList();
return res;
}
It gives me the error below:
FirstOrDefault()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
all the solutions given here haven't answered my query so far