Evonet
Evonet

Reputation: 3640

Error when retrieving entities with related entities using MVC 5 API Controller

I have an API Controller which retrieves a list of articles which works well. I've created a DTO class for my article which is used by my API controller, which includes a list of related objects (Tags).

The following code works well and retrieves my list of Articles:

public class ArticleDTO
{

    public int ArticleID { get; set; }

    public string Title { get; set; }

    public DateTime DatePublished { get; set; }

    [AllowHtml]
    public string Body { get; set; }

    public  ICollection<Tag> Tags { get; set; }
}

And my API controller (note that I'm not including Tags here in the linq query):

    private IQueryable<ArticleDTO> MapArticles()
    {
        return from p in db.Articles.Include("Tags")
               select new ArticleDTO() {    
                   ArticleID=p.ArticleID,
                   Title = p.Title,
                   Subheading = p.Subheading,
                   DatePublished = p.DatePublished,
                   Body = p.Body,
               };
    }

    public IEnumerable<ArticleDTO> GetArticles()
    {
        return MapArticles().AsEnumerable();
    }

However if I include Tags:

select new ArticleDTO() {    
    ArticleID=p.ArticleID,
    Title = p.Title,
    Subheading = p.Subheading,
    DatePublished = p.DatePublished,
    Body = p.Body,
    Tags = Tags
};

Then I get the following message:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

Type 'System.Data.Entity.DynamicProxies.Tag_5E08D5046E177BA781B97E38A79F1E2BCC3300645A0E505002547644006F116E' with data contract name 'Tag_5E08D5046E177BA781B97E38A79F1E2BCC3300645A0E505002547644006F116E:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

I don't know what this means or how to fix it, so would appreciate any help!

Thanks...

Upvotes: 1

Views: 1017

Answers (1)

Ivo
Ivo

Reputation: 8352

It's trying to serialize the Tags collection but it's composed by proxies. What you can do is to also have a TagDTO so you are sure what you are retrieving:

select new ArticleDTO() {    
    ArticleID=p.ArticleID,
    Title = p.Title,
    Subheading = p.Subheading,
    DatePublished = p.DatePublished,
    Body = p.Body,
    Tags = Tags.Select(t => new TagDTO {
                                         Name = t.Name
                                       })
    };

Upvotes: 1

Related Questions