0
var lstCatalog = context.Drinks_Category.Select(x => new { x.Id_category, x.Name_category, x.Parent}).ToList();

I have a table of 3 columns. I want to add a sequence number column, so how do I do it? Id_category is Key.

Thanks you!

My new code:

var lstCatalog = context.Drinks_Category.Select((x, i) => new { Index = i, x.Id_category, x.Name_category, x.Parent }).OrderByDescending(x=>x.Id_category).ToList();

and this error:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'System.Linq.IQueryable1[<>f__AnonymousType14[System.Int32,System.String,System.String,System.String]] Select[Drinks_Category,<>f__AnonymousType14](System.Linq.IQueryable1[BBModel.Drinks_Category], System.Linq.Expressions.Expression1[System.Func3[BBModel.Drinks_Category,System.Int32,<>f__AnonymousType1`4[System.Int32,System.String,System.String,System.String]]])' method, and this method cannot be translated into a store expression.'

1 Answers1

3

There is an overload of the Select extension that allows you to including the iteration index. You just need to add it in your select's lambda. You may want to combine this with an OrderBy first though, otherwise you'll get them in storage order (by your Drinks_Category clustered index).

var lstCatalog = context.Drinks_Category.Select((x, i) => new { i, x.Id_category, x.Name_category, x.Parent}).ToList();
Reddog
  • 15,219
  • 3
  • 51
  • 63