c# - 从与 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 中的 CategoryDescription 返回 null,显然是因为它没有正确映射。我可以用 automapper 做些什么来获取描述或如何完成它。
解决方案
推荐阅读
- scala - ApplicationLoader 内部是否存在隐式执行上下文
- python - 如何通过在python中排名将变量排序到其他变量中
- c++ - 将二维数组中的值输出到文本文件
- r - 如何平衡不平衡的面板数据?
- xml - 使用 Xpath 通配符获取所有标题字符串
- python - 通过python3从mysql获取数据
- c - 使用管道文件传输名称
- java - 我的 android 应用程序在尝试 10 次后崩溃
- javascript - 扩展/修补 HTMLScriptElement.prototype.attributes
- reactjs - 如何在反应框架中使用 mgt-people-picker