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!!!
Can you try:
Brian Cauthon's answer is excellent! Just a little update, for EF 6, the class got moved to another namespace. So, before EF 6, you should include:
If you update to EF 6, or simply are using this version, include:
By including the incorrect namespace with EF6, the code will compile just fine but will throw a runtime error. I hope this note helps to avoid some confusion.
If your "contact" is acting as generic list, I hope the following code works well.
Thanks.
My understanding is that you have to create a partial class to "extend" your model and add a property that is readonly that can utilize the rest of the class's properties.
Then
With EF v4 you can use
SqlFunctions.StringConvert
. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this:if you use entity framework and you want to make the only int acceptable then you can use this in linq query you can try this
it will work because using (int) will cast your value to the int so you don't need any conversion for string to int and you get the result you want.
this worked for me in my project i think it would be helpful for you