自身具有 child 的 C# AutoMapper

C# AutoMapper with a child of itself

你能在 objects 上与他们自己的 children 自动映射吗? 在这个例子中:

public class Book
{
    public int? BookKey { get; set; }
    public Categories bookCategories { get; set; }
}
public class Categories
{
    public int? CategoryKey { get; set; }
    public List<Book> RecommendedBooks { get; set; }
}


Mapper.CreateMap<Common.BookList, Book>().IgnoreAllNonExisting();
Mapper.AssertConfigurationIsValid();

Mapper.CreateMap<Common.Categories, Categories>().IgnoreAllNonExisting();
Mapper.AssertConfigurationIsValid();

交换最后两张地图每次都会导致错误。 book first,就是不懂分类,category first,就是不懂书。

AutoMapper.AutoMapperConfigurationException: Common.BookList / Common.Categories 上的以下 属性 无法映射。

您只需调用配置验证一次。多次使用它可以使调试更容易(这使您的异常更接近映射代码的位置),但在这种情况下,映射相互依赖(构建 [=11= 的映射] 需要 Automapper 知道如何映射 bookCategories)。

改成下面的代码,就可以正常工作了

Mapper.CreateMap<Common.BookList, Book>().IgnoreAllNonExisting();
Mapper.CreateMap<Common.Categories, Categories>().IgnoreAllNonExisting();
Mapper.AssertConfigurationIsValid();