Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get linq string & int concat for c# .net dropdown

public ViewResult Index()
{
     var theList = from p in db.theTable
                   select p.Id + p.lastName;

     ViewBag.theList = new SelectList(theList);                             
     return View();
}

The preceding code is in my controller and produces the following error:

"Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types."

I believe the problem is trying to concatenate an int (id) and string (lastName), as either alone works fine and I was able to concat firstName and lastName together.

I tried ToString() and Convert(), which did not work.

like image 852
user2182715 Avatar asked Dec 06 '25 03:12

user2182715


1 Answers

You need to use StringConvert

 var theList = from p in db.theTable
               select SqlFunctions.StringConvert((double)p.Id) + p.lastName;

But personally, I prefer to do string manipulation on the client. It gives you more flexibility with how you format your string anyway... like this

var theList = from p in db.theTable
               select new { p.Id, p.lastName };
ViewBag.theList = new SelectList(theList);   

...

@foreach(var p in ViewBag.theList)
{
    var str = string.Format("{0}{1}", p.Id, p.lastName);
} 
like image 99
p.s.w.g Avatar answered Dec 09 '25 02:12

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!