var items = from c in contacts
select new ListItem
{
Value = c.ContactId, //Cannot implicitly convert type 'int' (ContactId) to 'string' (Value).
Text = c.Name
};
var items = from c in contacts
select new ListItem
{
Value = c.ContactId.ToString(), //Throws exception: ToString is not supported in linq to entities.
Text = c.Name
};
Is there anyway I can achieve this? Note, that in VB.NET there is no problem use the first snippet it works just great, VB is flexible, im unable to get used to C#'s strictness!!!
Firstly, convert to object, then toString() will be correct.
One more solution:
Just add empty string and it will be converted to string.
Using MySql, the
SqlFunctions.StringConvert
didn't work for me. Since I useSelectListItem
in 20+ places in my project, I wanted a solution that work without contorting the 20+ LINQ statements. My solution was to sub-classSelectedListItem
in order to provide an integer setter, which moves type conversion away from LINQ. Obviously, this solution is difficult to generalize, but was quite helpful for my specific project.To use, create the following type and use in your LINQ query in place of
SelectedListItem
and use IntValue in place of Value.