c# - 从 Linq-to-Entities 中选择 Linq-to-XML?

标签 c# .net linq entity-framework 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)));

这是我现在唯一的选择,还是有另一种更清晰的代码表达方式?

最佳答案

在进行投影时使用 LINQ to Objects。为此,只需事先调用 AsEnumerable()

XElement xml = new XElement("People");

xml.Add(from p in peopleResults.AsEnumerable()
        select new XElement("Person",
            new XElement("Id", p.Id),
            new XElement("Name", p.Name)));

关于c# - 从 Linq-to-Entities 中选择 Linq-to-XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9263486/

相关文章:

C#——多线程

c# - Identity Server v3 自定义页面重置密码

c# - 为什么我不能将 LINQ 与 WorkItemCollection 一起使用

.net - JsonConverter 在集成测试中不起作用

c# - Linq 按类数组属性过滤

c# - linq 查询 : let with include statement

c# - 如何在不中断用户体验的情况下在后台轮询 webapi 请求?

c# - 仅更新模型的一部分,验证问题?

c# - 行号不正确的异常错误消息

.net - .NET 的智能卡身份验证