2010-08-12 55 views
7

我得到这个错误:“...无参数构造函数和初始化方法是否受支持......”错误是什么意思?

Only parameterless constructors and initializers are supported in LINQ to Entities. 

当尝试运行这段代码(发现这个代码here并取得测试数据库一起玩):

XElement xml = new XElement("contacts", 
        from c in db.Contacts 
        orderby c.ContactId 
        select new XElement("contact", 
           new XAttribute("contactId", c.ContactId), 
           new XElement("firstName", c.FirstName), 
           new XElement("lastName", c.LastName)) 
        ); 

其中自动生成数据库实体对象。任何想法如何让这个工作?

回答

6

我相信它反对的事实是,您使用的XElement构造函数在您的“select”子句中使用参数。由于XElement没有无参数构造函数,因此可能需要更改代码以选择匿名类型,并在事实之后初始化XElement集合。

var els = from c in db.Contacts 
      orderby c.ContactID 
      select new { c.ContactID, c.FirstName, c.LastName }; 

var xml = new XElement("contacts", 
    els.ToList() 
     .Select(e => new XElement("contact", 
         new XAttribute("contactID", e.ContactID), 
         new XElement("firstName", e.FirstName), 
         new XElement("lastName", e.LastName)))); 

这是未经测试,但希望给你的想法。我先做EF查询,然后调用ToList(),以便我可以使用Linq to Objects而不是EF来选择XElement集合。

+0

谢谢!这是重要的部分:)!我仍然对原始代码为什么不起作用感到困惑,我已经看到了其他类似的例子,创建XML文档。有任何想法吗? – Evan 2010-08-12 01:36:10

+0

由于错误,EF似乎不支持选择不具有无参数矩阵的对象。我不知道为什么存在这个限制,但是,把EF查询拉出等式解决了这个问题。 – 2010-08-12 02:16:50

+0

谢谢。这个答案今天帮了我。 – jessegavin 2011-03-31 22:02:28

1

我会改写这样的:

XElement xml2 = new XElement("contacts", 
        from c in 
        ((IEnumerable<Contact>)(from c in Contacts 
        orderby c.ContactId 
        select c)) 
       select new XElement("contact", 
         new XAttribute("contactId", c.ContactId), 
         new XElement("firstName", c.FirstName), 
         new XElement("lastName", c.LastName)) 
      ); 

点是从的XElement实例分离LINQ执行树。通过将LINQ查询从IQueriable转换为IEnumerable,您将分离LINQ将用于从将要创建XElements的代码中获取数据的代码。

+0

有趣的想法...我最近遇到了这个EF限制,并采用类似于@ Matt的解决方案。现在看[AsEnumerable文档](http://msdn.microsoft.com/en-us/library/bb335435.aspx),它看起来正是它的设计目的...... – shambulator 2011-09-14 15:46:09

相关问题