gpt4 book ai didi

entity-framework-4 - LINQ to Entities StringConvert(double)' 无法转换为将 int 转换为字符串

转载 作者:行者123 更新时间:2023-12-04 07:57:55 25 4
gpt4 key购买 nike

问题

需要使用 EF4 + SQL CE4 将 int 转换为 string。使用 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。

最佳答案

EF 在上层是独立于数据库的,但处理将 linq 查询转换为 SQL 的部分始终依赖于数据库和 SqlFunctions依赖于 SQL Server 提供程序,但您使用的 SQL Server CE 提供程序无法从 SqlFunctions 转换函数类(class)。

顺便提一句。第三个选项也不是解决方案,因为它会选择整个客户表到内存并在此之后使用 linq-to-objects。你应该使用这个:

public static IEnumerable<SelectListItem> xxGetCustomerList()
{
using (DatabaseEntities db = new DatabaseEntities())
{
// Linq to entities query
var query = from l in db.Customers
orderby l.CompanyName
select new { l.CustomerID, l.CompanyName };

// Result of linq to entities transformed by linq to objects
return query.AsEnumerable()
.Select(x => new SelectListItem
{
Value = x.CustomerID.ToString(),
Test = x.CompanyName
}).ToList();
}
}

关于entity-framework-4 - LINQ to Entities StringConvert(double)' 无法转换为将 int 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5771299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com