【问题标题】:Get data from relationship with AsyncCrudAppService从与 AsyncCrudAppService 的关系中获取数据
【发布时间】: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 中的 CategoryDe​​scription 正在返回 null,显然是因为它没有正确映射。我可以用 automapper 做些什么来获取描述或如何完成。

【问题讨论】:

  • 显示您如何配置从ItemItemDto 的映射。

标签: c# asp.net .net-core aspnetboilerplate


【解决方案1】:

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

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

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

【讨论】:

  • 我认为这是正确的答案,我希望默认获取相关实体。但是覆盖 CreateFilteredQuery 是一个简单的解决方案。
  • 您可以通过从AsyncCrudAppService 继承并覆盖该方法并使用反射来包含相关实体来实现包含所有相关实体的自己的版本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 2021-08-06
相关资源
最近更新 更多