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
};
有什么办法可以做到吗?
注意,在VB中。NET没有问题,使用第一个代码片段,它的工作只是伟大的,VB是灵活的,我无法习惯c#的严格!!
使用MySql, SqlFunctions。StringConvert不适合我。因为我在我的项目中使用SelectListItem在20多个地方,我想要一个解决方案,工作不扭曲20+ LINQ语句。我的解决方案是子类SelectedListItem,以提供一个整数setter,这将类型转换从LINQ。显然,这种解决方案很难概括,但对我的特定项目非常有帮助。
要使用,创建以下类型并在您的LINQ查询中使用SelectedListItem,并使用IntValue代替Value。
public class BtoSelectedListItem : SelectListItem
{
public int IntValue
{
get { return string.IsNullOrEmpty(Value) ? 0 : int.Parse(Value); }
set { Value = value.ToString(); }
}
}
使用MySql, SqlFunctions。StringConvert不适合我。因为我在我的项目中使用SelectListItem在20多个地方,我想要一个解决方案,工作不扭曲20+ LINQ语句。我的解决方案是子类SelectedListItem,以提供一个整数setter,这将类型转换从LINQ。显然,这种解决方案很难概括,但对我的特定项目非常有帮助。
要使用,创建以下类型并在您的LINQ查询中使用SelectedListItem,并使用IntValue代替Value。
public class BtoSelectedListItem : SelectListItem
{
public int IntValue
{
get { return string.IsNullOrEmpty(Value) ? 0 : int.Parse(Value); }
set { Value = value.ToString(); }
}
}