Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Why "Only parameterless constructors and initializers are supporte

$
0
0
This is the original code.
It exports blog articles to XML. The articles have a default constructor ("parameterless") and they have 3 fields which are ArticleId, Title and Content.

    [HttpGet]
    public ActionResult ExportXML()
    {
        var articles = new XElement("Articles",
            from article in _provider.Articles
            select new XElement("Article", new XAttribute("ArticleId", article.ArticleId),
                new XElement("Title", article.Title),
                new XElement("Content", article.Content))
            );

        var document = new XDocument(new XDeclaration("1.0", "utf-8", "true"), articles);
        return Content(document.ToString(), MIME.Text.Xml);
    }


It threw:

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

(All of my classes have a default/parameterless constructor).

There have been a few questions in SO for this exception but they didn't answer my question nor provided a solution. I found out the solution by messing a bit with the code and I found that when you invoke ToList() on _provider.Articles at the end of the first line inside the block it fixes the problem, but I don't understand why or what is the cause for the exception in the first place, and that is my question.

_provider.Articles is of type IQueryable<Article> that is retrieving data from a DbSet<Article> in a class that derives from DbContext. In this case it connects to a local database file.

Viewing all articles
Browse latest Browse all 51036

Trending Articles