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

问题描述 投票:0回答:1

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

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集合?

c# asp.net-web-api asp.net-core automapper
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.