问题
需要使用 EF4 + SQL CE4 将 int 转换为字符串。使用 SqlFunctions.StringConvert(double) 的推荐选项仍然给我错误。
选项 1(原件)。这给了我错误:
public static IEnumerable<SelectListItem> xxGetCustomerList()
{
using (DatabaseEntities db = new DatabaseEntities())
{
var list = from l in db.Customers
orderby l.CompanyName
select new SelectListItem { Value = l.CustomerID.ToString(), Text = l.CompanyName };
return list.ToList();
}
}
选项 2(最建议)。然后正如许多帖子所暗示的那样,我使用了 System.Data.Objects.SqlClient 库中的 SqlFunctions.StringConvert() 函数:
public static IEnumerable<SelectListItem> GetCustomerList()
{
using (DatabaseEntities db = new DatabaseEntities())
{
var list = from l in db.Customers
orderby l.CompanyName
select new SelectListItem { Value = SqlFunctions.StringConvert((double)l.CustomerID), Text = l.CompanyName };
return list.ToList();
}
}
现在显示以下错误:
The specified method 'System.String StringConvert(System.Nullable`1[System.Double])' on the type 'System.Data.Objects.SqlClient.SqlFunctions' cannot be translated into a LINQ to Entities store expression.
选项 3(针对非常具体的情况)。然后另一篇文章展示了一个使用 Dictionary 的智能解决方案,它最终可以工作:
public static IEnumerable<SelectListItem> xGetCustomerList()
{
using (DatabaseEntities db = new DatabaseEntities())
{
var customers = db.Customers.ToDictionary(k => k.CustomerID, k => k.CompanyName);
var list = from l in customers
orderby l.Value
select new SelectListItem { Value = l.Key.ToString(), Text = l.Value };
return list.ToList();
}
}
但仅适用于简单的对值(键、值)。有人可以帮我解决另一个问题,或者我在选项 2 上做错了什么吗?
我希望微软能在推动我们从已经稳定且更加成熟的 L2S 迁移之前尽快做出 EF。我实际上使用 EF4 只是因为想使用 SQL CE,否则我会留在 L2S。