什么“...无参数构造函数和初始化程序被支持......”错误意味着什么?

时间:2010-08-12 01:13:14

标签: entity-framework linq-to-entities linq-to-xml

我收到了这个错误:

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))
                    );

其中db是自动创建的实体对象。关于如何使其发挥作用的任何想法?

2 个答案:

答案 0 :(得分: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集合。

答案 1 :(得分: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))
            );

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

相关问题