2012-02-13 214 views
3

在混合LINQ到SQL和LINQ到XML,我曾经是能够做这样的事情:从Linq-to-Entities中选择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))); 

这是我唯一的选择,现在,还是有其他的代码来表达这种更清洁的方式?

回答

3

该方法是正确的。要稍微缩短它,您可以直接在对象上使用ToList方法。

XElement xml = new XElement("People"); 

xml.Add(from p in Context.People.ToList() 
     select new XElement("Person", 
      new XElement("Id", p.Id), 
      new XElement("Name", p.Name))); 
+0

在表中创建一个行的列表会在这里过大,因为这个列表从来没有真正用于枚举之外。 – 2012-02-13 18:42:59

+0

@JeffMercado正确。 ToList在这种情况下是过分的,因为查询在Add中被消耗,并且不需要考虑顺从。 – 2012-02-13 19:58:43

6

当你做投影时使用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)));