[英]Cast the type 'System.Int64' to type 'System.Object'
I'm trying to export a SQL query result to an CSV file, but i'm having some issues with the cast. 我正在尝试将SQL查询结果导出到CSV文件,但是我在转换时遇到了一些问题。
here's my code : 这是我的代码:
var query = string.Concat((from t in db.employees select t.ID + "," + t.LastName+"\n" ).Take(2000));
return File(new System.Text.UTF8Encoding().GetBytes(query), "text/csv", "Report.csv");
But i have the following error : Additional information: Unable to cast the type 'System.Int64' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
但是我有以下错误:
Additional information: Unable to cast the type 'System.Int64' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
Additional information: Unable to cast the type 'System.Int64' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
Can you help me on this ? 你能帮我吗? Thanks
谢谢
You may need to query the data and do the string projection in two steps: 您可能需要查询数据并分两步进行字符串投影:
var query =
(from t in db.employees
select new {t.ID , t.LastName})
.Take(2000)
.AsEnumerable();
var csv = string.Concat(query.Select(t => t.ID + "," + t.LastName + "\n"));
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report.csv");
It looks like EF is unable to translate your string concatenation call to SQL. 看来EF无法将您的字符串连接调用转换为SQL。 You should be able to work around this issue by concatenating in memory:
您应该可以通过串联内存来解决此问题:
var query = string.Concat(
db.employees
.Select(e => new {ID, LastName})
.Take(2000)
.AsEnumerable() // The rest of the query happens in memory
.Select(p => p.ID + "," + p.LastName)
);
Just to post my theory: 只是发表我的理论:
var query = string.Concat(
(from t in db.employees select t.ID + "," + t.LastName+"\n" )
.Take(2000)
.ToArray());
The difference is the final .ToArray()
. 区别在于最终的
.ToArray()
。 string.Concat(IEnumerable<string>)
was introduced in .NET 4.0 . .NET 4.0中引入了
string.Concat(IEnumerable<string>)
。 Perhaps you are using an older version of .NET . 也许您正在使用.NET的旧版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.