0

Settings: asp.net mvc web app, azure sql db, EF code-first project

I am trying to combine 3 strings and a short into one string as given below:

CompanyAddress = company.ZipCode.ToString() + " " + company.City + ", " + company.Street + " " + company.StreetNr

ZipCode is a short, all others are strings. Using this code in a controller action returns no records (and no error message when run). When I omit the ZipCode part I get all records.

I also have tried ToString(company.ZipCode) and without .ToString(). Gives a wiggle-line (does not compile) and when run no error message and no records in return, respectively. Please help.

Additional info: The code line is part of an api controller (see below), ZipCode is nullable. When ZipCode is part of the code line, then the controller delivers null, otherwise it delivers a proper string.

        var companies = UnitOfWork.GetAll<Company>();
        var query = company in companies
                    where company.Activ == true

                    select new ActiveCompaniesViewModel
                    {
                        CompanyAddress = company.ZipCode.ToString() + " " + company.City + ", " + company.Street + " " + company.StreetNr
                    };

        return query;
Manu
  • 1,290
  • 5
  • 17
  • 32

2 Answers2

1

This has been answered before, Problem with converting int to string in Linq to entities

I think this will be your solution,

select new ActiveCompaniesViewModel
{
    CompanyAddress = (company.ZipCode == null ? "" : SqlFunctions.StringConvert((int)company.ZipCode) + " ") +
                     company.City + ", " +
                     company.Street + " " +
                     company.StreetNr
};
Community
  • 1
  • 1
ProgrammerGuy
  • 439
  • 3
  • 15
0

That worked (does not make sense to me though!):

CompanyAddress = SqlFunctions.StringConvert((decimal?)company.ZipCode) + " " + company.City + ", " +
                            company.Street + " " +
                            company.StreetNr,
Manu
  • 1,290
  • 5
  • 17
  • 32
  • ToString() on a short doesn't work as expected on LINQ to Entities, so we're using SqlFunction.StringConvert to do the conversion instead – ProgrammerGuy Mar 25 '17 at 19:46
  • I understand why we need SqlFunctions.StringConvert, but why 'decimal' is needed for a conversion from short to string seems strange to me. – Manu Mar 26 '17 at 08:07