mar*_*cer 1 c# linq asp.net-mvc entity-framework asp.net-web-api
我有WebAPI控制器从表数据生成XML
这是代码
public class XMLController : ApiController
{
private trackingappEntities db = new trackingappEntities();
[HttpGet]
public HttpResponseMessage Index()
{
var xdoc = new XDocument(
new XElement("data",
db.TimeTables.Select(w =>
new XElement("worker",
new XAttribute("id", w.INN),
new XElement("start", w.StartDay),
new XElement("pause", w.StartPause),
new XElement("continue", w.EndPause),
new XElement("end", w.EndDay)
)
)
)
);
return new HttpResponseMessage() { Content = new StringContent(xdoc.ToString(), Encoding.UTF8, "application/xml") };
}
}
Run Code Online (Sandbox Code Playgroud)
这是TimeTable类
public partial class TimeTable
{
public int Id { get; set; }
public string Company { get; set; }
public string INN { get; set; }
public string StartDay { get; set; }
public string StartPause { get; set; }
public string EndDay { get; set; }
public string EndPause { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是当我发送请求时,我有这个回复
LINQ to Entities中仅支持无参数构造函数和初始值设定项.
我怎么解决这个问题?
LINQ的工作原理是检查函数调用的代码,而不仅仅是结果.
在您的情况下,可能的解决方案是AsEnumerable在调用构造函数之前调用告诉LINQ从SQL填充每个记录.
var timeTables = db.TimeTables
/*
* Select is optional; this would improve performance for a table with many
* extra properties, but would have little-to-no relevant impacts if you're
* already using them all. Similar to a SELECT * versus selecting individual
* columns.
*/
.Select(c => new {
c.INN,
c.StartDay,
c.StartPause,
c.EndPause,
c.EndDay
})
.AsEnumerable(); // or ...await ToListAsync();
var xdoc = new XDocument(
new XElement("data",
timeTables.Select(w =>
new XElement("worker",
new XAttribute("id", w.INN),
new XElement("start", w.StartDay),
new XElement("pause", w.StartPause),
new XElement("continue", w.EndPause),
new XElement("end", w.EndDay)
)
)
)
);
Run Code Online (Sandbox Code Playgroud)
否则,您可以想象LINQ尝试基本上发送逻辑以XElement直接生成SQL.由于SQL无法理解该过程中涉及的逻辑,因此LINQ抛出.
在此示例中,Select调用构建匿名类型.因为它保证在构造函数中没有执行额外的逻辑,所以LINQ能够简单地选择这些值,并将它们填充到C#-side.