0

I have been searching in Google: linq to entities does not recognize the method int32 toint32. I have this list in my database like varchar:

1 , 2 , 3 , 4 , 5 , 6 , 7 .

I need to order that list and get the max value. I'm using this but it doesn't work, I too saw other solutions here, but nothing works. This is my query:

var query= dbcontext.NV_Users.OrderBy(p => Convert.ToUInt32(p.code)).ToList().Max();

And I was trying with a normal query, also not working:

var query= from _NV_Field in dbcontext.NV_Users
           orderby Convert.ToInt32(_NV_Field.code) ascending
           select _NV_Field.code;

Before asking here , I've been searching Google like a crazy.

Abbas
  • 14,186
  • 6
  • 41
  • 72
TSW1985
  • 1,179
  • 2
  • 10
  • 13
  • 1
    Why are you using `.Max`? What do you want to accomplish, ie. a textual description of the result you want, can you provide that? – Lasse V. Karlsen Sep 01 '14 at 12:44

2 Answers2

0

Since you are using .ToList(), you may just change the order of your functions:

var query= dbcontext.NV_Users.ToList().OrderBy(p => Convert.ToUInt32(p.code)).Max();
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
  • Really? If it's a big list, it would be much better to do the sorting on the database. – Rawling Sep 01 '14 at 12:40
  • 1
    Whilst this will indeed avoid the error, the OrderBy is still pointless as he is calling Max(), which returns a single value. – Ben Robinson Sep 01 '14 at 12:40
  • @Rawling If the list is that big, data shouldn't be fetched from DB _at all_. As OP already uses `ToList()`, one can assume the number of items in the database is relatively small. Plus the fact ordering is actually pointless in that case. – ken2k Sep 01 '14 at 12:42
  • @ken2k There's a lot odd going on here (`ToList` and `Max`, `Max` on a complex type), so I'm pointing out that reodering stuff probably isn't going to help. – Rawling Sep 01 '14 at 12:43
  • I really aggree with all the comments here. ToList should be used with cotion as it could lead to fetching data that might not be needed. Also the Max troubled me too. I really know that there are cases that the OP hides us info, so i did not want to change his query much. – Giannis Paraskevopoulos Sep 01 '14 at 12:45
0

Finally I found the solution. I need convert the field on the select

 var consulta = from _NV_Fabricantes in dbcontext.NV_Fabricantes.ToList().OrderBy(p =>     Convert.ToInt32(p.codigo)) 
                            select Convert.ToInt32(_NV_Fabricantes.codigo);
TSW1985
  • 1,179
  • 2
  • 10
  • 13