What does "constructors without parameters and initializers ..." mean?

I get this error:

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

When trying to run this code (here this code is here and made the test database play with):

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

where db is the object of automatically created objects. Any ideas on how to make this work?

+7
linq-to-entities linq-to-xml entity-framework
source share
2 answers

I believe that he objects to the fact that you are using the XElement constructor, which takes parameters in your select clause. Since XElement does not have a constructor without parameters, you may need to modify your code to select an anonymous type, and initialize the XElement collection after the fact.

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

This is untested, but hopefully gives you this idea. First I make an EF request, and then I call ToList () so that I can select the XElement collection using Linq for objects, not EF.

+6
source share

I would rewrite it as follows:

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

The goal is to separate the LINQ runtime tree from the XElement instance. By extracting a LINQ query from IQueriable to IEnumerable, you separate the code that LINQ will use to retrieve data from the code that your XElements will create.

+1
source share

All Articles