0

I have a linq query that returns a public class. In select new I access a property Cruising through entities database and add the value but jumps except where it says:

LINQ to Entities does not recognize the 'System.String ToString ()' method of the method, and this method can not be translated into a store expression.

where is the problem? I can navigate in a Linq .Select across linq to bd navigation properties really?

I tried to make the .Sum of several ways but I failed.

I would appreciate help.

thanks

  public class prueba
{
    public int Id { get; set; }
    public string Nombre { get; set; }
    public string Email { get; set; }
    public string Codigo { get; set; }
    public string Total { get; set; }

}
var result = db.cliente
                       .Where(p => !p.Baja.Value)
                       .Where(OperacionPedido(operacionPedid, numPedidos))
                       .Where(OperacionGastado(operacionTot, totGastado))
                       .Select(p => new prueba
                       {
                           Id = p.Id,
                           Nombre = p.Nombre + " " + p.Apellidos,
                           Email = p.Email,
                           Codigo = p.territorio1.Codigo_iso3166_3.Trim(),
                           Total = p.pedido.Sum(oo=>oo.Total.Value).ToString() 
                       }).OrderBy(p => p.Nombre)
                       .ToList();
Raúl
  • 15
  • 1
  • 6
  • 1
    As the error suggests, the problem is not in `Sum`, but in `ToString`. I'd suggest making `Total` an numeric type, so you don't have to call `ToString`. – p.s.w.g Feb 10 '14 at 16:51
  • possible duplicate of [LINQ to Entities does not recognize the method 'System.String ToString()' method, - MVC4](http://stackoverflow.com/questions/18233495/linq-to-entities-does-not-recognize-the-method-system-string-tostring-method) – Gert Arnold Feb 10 '14 at 21:07
  • Thanks p.s.w.g, your solution is good, I preferred to return a string but in the end will be better to return a decimal. thanks – Raúl Feb 11 '14 at 07:25

1 Answers1

0

Use SqlFunctions.StringConvert instead of ToString so your Sum query

Total = p.pedido.Sum(oo=>oo.Total.Value).ToString()

should be:

Total = SqlFunctions.StringConvert(p.pedido.Sum(oo=>oo.Total.Value))

LINQ queries with Entity framework translates into underlaying data source language, (in your case SQL probably), and ToString can't be translated into SQL by Entity framework. That is why SqlFunctions.StringConvert is provided.

It is not a good idea to store numeric value in String type, instead you should use int or double type for your field Total.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • The only caveat is that `SqlFunction` will tie you (and work only) with SQL Server. – Simon Belanger Feb 10 '14 at 16:55
  • Right Simon and Habib, is good solution too but in the end i'll to return a decimal and i will not return string. Thanks very much – Raúl Feb 11 '14 at 07:23