首页 > 解决方案 > 从与 AsyncCrudAppService 的关系中获取数据

问题描述

我正在使用 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 中的 CategoryDe​​scription 返回 null,显然是因为它没有正确映射。我可以用 automapper 做些什么来获取描述或如何完成它。

标签: c#asp.net.net-coreaspnetboilerplate

解决方案


我认为您的映射是正确的,但问题是您没有获得相关实体,因为AsyncCrudAppService默认情况下不会包含任何关系。(检查GetAllAsync方法实现here

您需要通过覆盖方法自己包含它(在此处CreateFilteredQuery检查实现)

return Repository.GetAll().Include(x=>x.Category);

推荐阅读