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

Eva*_*van 7 linq-to-entities entity-framework linq-to-xml

我收到这个错误:

Only parameterless constructors and initializers are supported in LINQ to Entities.
Run Code Online (Sandbox Code Playgroud)

尝试运行此代码时(在此处找到此代码并使测试数据库可以使用):

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))
                    );
Run Code Online (Sandbox Code Playgroud)

其中db是自动创建的实体对象.有关如何使其工作的任何想法?

Mat*_*ton 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))));
Run Code Online (Sandbox Code Playgroud)

这是未经测试的,但希望能给你这个想法.我首先进行EF查询,然后在其上调用ToList(),以便我可以使用Linq to Objects而不是EF来选择XElement集合.