0

I have a db call that returns me an object. I use linq to cast that object how I want it

var result = queryResult.OrderBy(c => c.TariffName)
                        .Take(count)
                        .Select(c => new
                            {
                                Text = c.TariffName,
                                Key = c.TariffId,
                                Price = c.LineRental
                            });

var list = result.ToList();

I now want to add the line rental to the tariff name show that it shows like:

myTariff - 12.99

when I try and do this though I can make this change ok:

Text = c.TariffName + " - ",

but when I try and add the line rental I get problems that linq won't recognise the ToString(). I need it to look like:

Text = c.TariffName + " - " + c.LineRental.ToString(),

I understand that linq won't recognise the ToString() method from reading LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression but how do I change this given I can't set it as a string prior to the linq query?

Community
  • 1
  • 1
GrahamJRoy
  • 1,603
  • 5
  • 26
  • 56
  • You can use loop to fill the result object. In loops's body you can use `Text = c.TariffName + " - " + c.LineRental.ToString()` – Adil Ansari Mar 01 '16 at 12:38

2 Answers2

1

Convert the query result to a list first then use select to make the toString work.

var result = queryResult.OrderBy(c => c.TariffName)
                        .Take(count);
var list = result.ToList().Select(c => new
                            {
                                Text = c.TariffName + " - " + c.LineRental.ToString(),
                                Key = c.TariffId,
                                Price = c.LineRental
                            });
Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33
-1

What is happening linq trying to execute your select statement on the database query level, and it does not know how to transform your .Select lambda to select part of sql statement.

Easiest thing you can do is first query required fields, call .ToList() on query to execute it and perform projection after that.

var result = queryResult.OrderBy(c => c.TariffName)
                    .Take(count)

                    .Select(c => new
                        {
                            Text = c.TariffName,
                            Key = c.TariffId,
                            Price = c.LineRental
                        });

var list = result.ToList().Select(c=>new {
          Text = string.Format("{0} - {1}", c.Text, c.Price),
          Key=Key,
          Price=Price
});
vittore
  • 17,449
  • 6
  • 44
  • 82