[英]How to map a DTO with a many-to-many relationship to a EF core entity with a relationship table using automapper?
[英]Auto mapping (with AutoMapper) from DTO to an entity with many-to-many relationship in it
我遇到了以下示例中反映的问题。 我已经在BookController中创建了一个POST方法来创建Book实体:
这是我的代码:
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public virtual ICollection<BookCategory> BookCategories { get; set; }
}
public class BookCategory
{
public int BookId { get; set; }
public virtual Book Book { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
我的DTO:
public class BookDto
{
public int BookId { get; set; }
public string Title { get; set; }
public ICollection<CategoryDto> Categories { get; set; }
}
public class CategoryDto
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
自动映射器配置:
CreateMap<Book, BookDto>().ReverseMap();
CreateMap<BookCategory, CategoryDto>()
.ForMember(d => d.CategoryId, opt => opt.MapFrom(s => s.CategoryId))
.ForMember(d => d.CategoryName, opt => opt.MapFrom(s => s.Category.CategoryName));
CreateMap<CategoryDto, BookCategory>().ForMember(d => d.CategoryId, opt => opt.MapFrom(s => s.CategoryId));
CreateMap<BookDto, Book>().AfterMap((s, d) =>
{
foreach (var bookCategory in d.BookCategories)
{
bookCategory.BookId = s.BookId;
}
});
这是我要映射到实体的DTO:
BookDto model = new BookDto()
{
Title = "Test book",
Categories = new List<CategoryDto>()
{
new CategoryDto()
{
CategoryId = 1,
CategoryName = "drama"
}
},
};
BookDto是一本新书,但是它指向现有的类别。 在数据库中已经存在Category.Id = 1,其中“ drama”作为CategoryName。 当前问题在于映射:
CreateMap<BookDto, Book>().AfterMap((s, d) =>
{
foreach (var bookCategory in d.BookCategories)
{
bookCategory.BookId = s.BookId;
}
});
当上面的代码即将执行时,d.BookCategories为null。 所以我想知道我的映射有什么问题吗?
AutoMapper自动映射具有相同名称的成员。 由于Book
和BookDto
集合具有不同的名称( BookCategories
与Categories
),因此必须对其进行显式映射。 您可以在其中一张地图中执行此操作,而ReverseMap
将处理相反的情况:
CreateMap<Book, BookDto>()
.ForMember(d => d.Categories, opt => opt.MapFrom(s => s.BookCategories))
.ReverseMap()
.AfterMap((s, d) =>
{
foreach (var bookCategory in d.BookCategories)
bookCategory.BookId = s.BookId;
});
但是由于BookCategory
实体仅包含2个id,因此可以避免从CategoryDto
到BookCategory
和AfterMap
的映射,并使用简单的LINQ投影(`Select')进行反向映射:
CreateMap<Book, BookDto>()
.ForMember(d => d.Categories, opt => opt.MapFrom(s => s.BookCategories))
.ReverseMap()
.ForMember(d => d.BookCategories, opt => opt.MapFrom(s => s.Categories
.Select(c => new BookCategory { BookId = s.BookId, CategoryId = c.CategoryId })));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.