从 Linq-to-Entities 中选择 Linq-to-XML?
在混合 Linq-to-SQL 和 Linq-to-XML 时,我曾经能够执行以下操作:
XElement xml = new XElement("People");
xml.Add(from p in Context.People
select new XElement("Person",
new XElement("Id", p.Id),
new XElement("Name", p.Name)));
在将一些内容转换为 EF 时,我现在遇到此异常:“LINQ to Entities 仅支持无参数构造函数和初始化程序” ”。
这让我相信我现在需要做这样的事情:
XElement xml = new XElement("People");
var peopleResults = Context.People.Select(p => { p.Id, p.Name }).ToList();
xml.Add(from p in peopleResults
select new XElement("Person",
new XElement("Id", p.Id),
new XElement("Name", p.Name)));
这是我现在唯一的选择,还是有另一种更清晰的方式在代码中表达这一点?
In mixing Linq-to-SQL and Linq-to-XML, I used to be able to do something like this:
XElement xml = new XElement("People");
xml.Add(from p in Context.People
select new XElement("Person",
new XElement("Id", p.Id),
new XElement("Name", p.Name)));
In converting some stuff to EF, I now get this exception: "Only parameterless constructors and initializers are supported in LINQ to Entities."
This leads me to believe I now need to do something like this:
XElement xml = new XElement("People");
var peopleResults = Context.People.Select(p => { p.Id, p.Name }).ToList();
xml.Add(from p in peopleResults
select new XElement("Person",
new XElement("Id", p.Id),
new XElement("Name", p.Name)));
Is this my only alternative now, or is there another cleaner way to express this in code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
进行投影时使用 LINQ to Objects。为此,只需预先调用
AsEnumerable()
即可。Use LINQ to Objects when you do the projection. To do that, just call
AsEnumerable()
beforehand.做法是正确的。要稍微缩短它,您可以直接在对象上使用 ToList 方法。
The approach is correct. To shorten it slightly you can use the ToList method on the object directly.