Asp.net core EF core中的automapper和多对多关系
我有两个具有多对多关系和联接表的模型:Asp.net core EF core中的automapper和多对多关系,asp.net-core,ef-code-first,mapping,entity-framework-core,automapper,Asp.net Core,Ef Code First,Mapping,Entity Framework Core,Automapper,我有两个具有多对多关系和联接表的模型: public class Book { [Key] public int BookId { get; set; } public string Name { get; set; } public string AuthorName { get; set; } public int YearOfPublishing { get; set; } publi
public class Book
{
[Key]
public int BookId { get; set; }
public string Name { get; set; }
public string AuthorName { get; set; }
public int YearOfPublishing { get; set; }
public LibraryType Type { get; set; }
public ICollection<BookPublicHouse> PublicHouses { get; set; }
public Book()
{
PublicHouses = new Collection<BookPublicHouse>();
}
}
public class PublicHouse
{
[Key]
public int PublicHouseId { get; set; }
public string PublicHouseName { get; set; }
public string Country { get; set; }
public ICollection<BookPublicHouse> Books { get; set; }
public PublicHouse()
{
Books = new Collection<BookPublicHouse>();
}
}
public class BookPublicHouse
{
public Book Book { get; set; }
public int BookId { get; set; }
public PublicHouse PublicHouse { get; set; }
public int PublicHouseId { get; set; }
}
公共课堂教材
{
[关键]
public int BookId{get;set;}
公共字符串名称{get;set;}
公共字符串AuthorName{get;set;}
公开发布{get;set;}
公共库类型{get;set;}
公共ICollection酒店{get;set;}
公共书籍()
{
公共场所=新收藏();
}
}
公营酒店
{
[关键]
public int PublicHouseId{get;set;}
公共字符串PublicHouseName{get;set;}
公共字符串国家{get;set;}
公共ICollection图书{get;set;}
公共招待所()
{
书籍=新收藏();
}
}
公营书屋
{
公共图书{get;set;}
public int BookId{get;set;}
公共酒店公共酒店{get;set;}
public int PublicHouseId{get;set;}
}
然后我需要将视图模型映射到模型。
视图模型如下所示:
public class BookView
{
public int BookId { get; set; }
public string Name { get; set; }
public string AuthorName { get; set; }
public int YearOfPublishing { get; set; }
public LibraryType Type { get; set; }
public IEnumerable<PublicHouseView> PublicHouses { get; set; }
}
公共类图书视图
{
public int BookId{get;set;}
公共字符串名称{get;set;}
公共字符串AuthorName{get;set;}
公开发布{get;set;}
公共库类型{get;set;}
公共IEnumerable酒店{get;set;}
}
创建地图:
CreateMap<Book, BookView>()
.ForMember(bv => bv.PublicHouses, opt => opt.MapFrom(x => x.PublicHouses.Select(y => y.PublicHouse).ToList()));
CreateMap()
.ForMember(bv=>bv.publichhouse,opt=>opt.MapFrom(x=>x.publichhouse.Select(y=>y.publichhouse.ToList());
但我有一个例外(映射类型错误、缺少类型映射配置或不支持的映射)。
)在这里:
public IEnumerable Get()
{
var books=\u context.books
.Include(b=>b.publichhouse).然后Include(bph=>bph.publichhouse).ToList();
返回mapper.Map(书籍);
}
哪里是酒店视图
类和来自酒店的映射
?听起来像是重复的,但也显示了完整的异常。
public IEnumerable<BookView> Get()
{
var books = _context.Books
.Include(b => b.PublicHouses).ThenInclude(bph => bph.PublicHouse).ToList();
return mapper.Map<List<Book>, List<BookView>>(books);
}