【发布时间】:2021-11-20 14:24:33
【问题描述】:
我正在使用 asp.net 样板,我想从 api 调用返回具有必须从实体关系中获取的属性的 DTO。
服务很简单,继承自 AsyncCrudAppService:
public class ItemAppService : AsyncCrudAppService<Core.Item, ItemDto>, IItemAppService
{
...
}
在请求返回 ItemDTO 的任何 Get 或 GetAll 方法时,我需要从类别(即关系,见下文)中获取描述。
public class ItemDto : EntityDto
{
public string Name { get; set; }
public int? CategoryId { get; set; }
public string CategoryDescription { get; set; }
}
为了澄清,我有以下两个实体有关系。
public class Item : Entity {
public string Name { get; set; }
public int? CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public class Category : Entity {
public string Description { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
在EntityFrameworkCore映射中产生如下关系:
...
public void Configure(EntityTypeBuilder<Item> builder)
{
builder.HasOne<Category>(e => e.Category).WithMany(c => c.Items).HasForeignKey(c => c.CategoryId);
}
自动映射器配置文件配置:
public class ItemProfile : Profile
{
public ItemProfile()
{
CreateMap<ItemDto, Core.Item>();
CreateMap<Core.Item, ItemDto>()
.ForMember(p => p.CategoryDescription, options => options.MapFrom(x => x.Category.Description));
}
}
现在 ItemDto 中的 CategoryDescription 正在返回 null,显然是因为它没有正确映射。我可以用 automapper 做些什么来获取描述或如何完成。
【问题讨论】:
-
显示您如何配置从
Item到ItemDto的映射。
标签: c# asp.net .net-core aspnetboilerplate