【发布时间】:2011-05-05 15:20:08
【问题描述】:
问题
需要使用 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。
【问题讨论】:
-
可能是因为我使用的是 SQL CE?而不是 SQL 或 SQL Express?我阅读了其他使用 MySQL 遇到同样问题的帖子。 EF4 应该独立于数据库,不是吗?
标签: entity-framework-4 linq-to-entities sql-server-ce-4