自动映射器忽略集合对象中的子属性

时间:2018-09-14 08:45:15

标签: c# asp.net-web-api asp.net-core automapper

我有相关的文章和类别模型:

public class Article
{
    ...

    public Category Category { get; set; }
}

 public class Category
 {
     ...

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

这些是他们的ModelViews:

public class ArticleViewModel
{
    ...

    public CategoryViewModel Category { get; set; }
}

public class CategoryViewModel
{
    ...

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

这就是Automapper:

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

代码会遇到此错误:

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

获取文章时如何忽略Category.Articles中的AutoMapper集合?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码

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

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