我正在尝试将SQL查询结果导出到CSV文件,但我遇到了一些问题。
这是我的代码:
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");
但我有以下错误:Additional information: Unable to cast the type 'System.Int64' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
答案 0 :(得分:0)
您可能需要分两步查询数据并进行字符串投影:
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");
答案 1 :(得分:0)
看起来EF无法将您的字符串连接调用转换为SQL。您应该能够通过在内存中连接来解决此问题:
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)
);
答案 2 :(得分:0)
发表我的理论:
var query = string.Concat(
(from t in db.employees select t.ID + "," + t.LastName+"\n" )
.Take(2000)
.ToArray());
差异是最终的.ToArray()
。 {4.0}中引入了string.Concat(IEnumerable<string>)
。也许您使用的是旧版本的.NET。