wanjydan
wanjydan

Reputation: 139

Automapper ignore child property in a collection object

I have Article and Category models which are related:

public class Article
{
    ...

    public Category Category { get; set; }
}

 public class Category
 {
     ...

     public ICollection<Article> Articles { get; set; }
 }

These are their ModelViews:

public class ArticleViewModel
{
    ...

    public CategoryViewModel Category { get; set; }
}

public class CategoryViewModel
{
    ...

    public ICollection<ArticleViewModel> Articles { get; set; }
}

And this the Automapper:

CreateMap<Article, ArticleViewModel>()
.ReverseMap();

The code runs in to this error:

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected with type 'ArticleViewModel'. Path 'category.articles'.

How can i ignore Category.Articles collection in the AutoMapper when getting the article?

Upvotes: 0

Views: 1101

Answers (1)

Md. Abdul Alim
Md. Abdul Alim

Reputation: 689

You can try with this code

var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };

            return JsonConvert.DeserializeObject</*your type*/>(JsonConvert.SerializeObject(/*your source*/, Formatting.None, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }), deserializeSettings);

Upvotes: 1

Related Questions