我有相关的文章和类别模型:
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
集合?
您可以尝试使用此代码
var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
return JsonConvert.DeserializeObject</*your type*/>(JsonConvert.SerializeObject(/*your source*/, Formatting.None, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }), deserializeSettings);