首页 > 解决方案 > Automapper 不使用获取请求映射依赖实体

问题描述

当我直接从数据库调用对象模型变量时,我会收到有关依赖实体的所有所需数据:MenuItem。

当我使用自动映射器时,它会将映射的 MenuItem 对象显示为空。getAll 和 getAllById 的自动映射有效。

主体实体:ItemCategory DependentEntity:MenuItem

请帮忙。

映射配置文件:

 public class MappingProfile: Profile
    {
        public MappingProfile()
        {
            CreateMap<ItemCategory, ItemCategoryDto>();
            CreateMap<ItemType, ItemTypeDto>();
            CreateMap<ItemStatus, ItemStatusDto>();

            CreateMap<MenuItem, MenuItemDto>();
            //CreateMap<ItemCategory, ItemCategoryDto>();
            //CreateMap<ItemType, ItemTypeDto>();
            //CreateMap<ItemStatus, ItemStatusDto>();

        }
    }

ItemCategory 模型类:

public partial class ItemCategory
    {
        public ItemCategory()
        {
            MenuItem = new HashSet<MenuItem>();
        }

        public Guid Id { get; set; }
        public string Description { get; set; }

        public virtual ICollection<MenuItem> MenuItem { get; set; }
    }

MenuItem 模型类:

public partial class MenuItem
    {
        public MenuItem()
        {
            Menu = new HashSet<Menu>();
            MenuItemAllergy = new HashSet<MenuItemAllergy>();
            MenuItemIngredient = new HashSet<MenuItemIngredient>();
            MenuItemPrice = new HashSet<MenuItemPrice>();
            MenuItemSpecial = new HashSet<MenuItemSpecial>();
            OrderMenuItem = new HashSet<OrderMenuItem>();
        }

        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public Guid ItemCategoryId { get; set; }
        public Guid ItemTypeId { get; set; }
        public Guid ItemStatusId { get; set; }

        public virtual ItemCategory ItemCategory { get; set; }
        public virtual ItemStatus ItemStatus { get; set; }
        public virtual ItemType ItemType { get; set; }
        public virtual ICollection<Menu> Menu { get; set; }
        public virtual ICollection<MenuItemAllergy> MenuItemAllergy { get; set; }
        public virtual ICollection<MenuItemIngredient> MenuItemIngredient { get; set; }
        public virtual ICollection<MenuItemPrice> MenuItemPrice { get; set; }
        public virtual ICollection<MenuItemSpecial> MenuItemSpecial { get; set; }
        public virtual ICollection<OrderMenuItem> OrderMenuItem { get; set; }
    }

项目类别 DTO:

public class ItemCategoryDto
    {

        public Guid Id { get; set; }
        public string Description { get; set; }

        public IEnumerable<MenuItemDto> MenuItems { get; set; }
    }

菜单项DTO:

public class MenuItemDto
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

    }

ItemCategory 接口:

public interface IItemCategory: IRepositoryBase<ItemCategory>
    {
        IEnumerable<ItemCategory> GetAllItemCategories();
        ItemCategory GetItemCategoryById(Guid categoryId);
        ItemCategory GetItemCategoryWithDetails(Guid categoryId);
    }

ItemCategory 存储库:

public class ItemCategoryRepository: RepositoryBase<ItemCategory>, IItemCategory
    {
        public ItemCategoryRepository(eWaiterTestContext repositoryContext)
            : base(repositoryContext)
        {
        }

        public IEnumerable<ItemCategory> GetAllItemCategories()
        {
            return FindAll()
                .OrderBy(ic => ic.Description)
                .ToList();
        }

        //Can Add Find By description same way
        public ItemCategory GetItemCategoryById(Guid categoryId)
        {
            return FindByCondition(x => x.Id.Equals(categoryId))
                .FirstOrDefault();
        }

        public ItemCategory GetItemCategoryWithDetails(Guid categoryId)
        {
            return FindByCondition(x => x.Id.Equals(categoryId))
                    .Include(z=>z.MenuItem)
                    .FirstOrDefault();
        }
    }

ItemCategory 控制器返回带有相关菜单项的 ItemCategory:

 [HttpGet("{id}/menuItem")]
        public IActionResult GetItemCategoryWithDetails(Guid id)
        {
            try
            {
                var category = _repository.ItemCategory.GetItemCategoryWithDetails(id);

                if (category == null)
                {
                    _logger.LogError($"Category with id: {id}, hasn't been found in db.");
                    return NotFound();
                }
                else
                {
                    _logger.LogInfo($"Returned owner with details for id: {id}");

                    var result = _mapper.Map<ItemCategoryDto>(category);
                    return Ok(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside GetItemCategoryWithDetails action: 
                 straight from the database{ex.Message}");
                return StatusCode(500, "Internal server error");
            }
        }

标签: asp.net-coreautomapperrepository-pattern

解决方案


属性的名称必须相同,但您只是跳过了 ItemCategory 模型的 's'

ItemCategory 模型类:

public partial class ItemCategory {
    public virtual ICollection<MenuItem> MenuItem { get; set; }
}

ItemCategoryDto 模型类:

public partial class ItemCategoryDto {
    public virtual ICollection<MenuItem> MenuItems { get; set; }
}

或者你可以像这样设置 AutoMapper :)

public class CategoryMapper: Profile
{
    public CategoryMapper()
    {
        CreateMap<ItemCategory, ItemCategoryDto>()
            .ForMember(x => x.MenuItems, x => x.MapFrom(src => src.MenuItem));
    }
}

并将其注入 Startup.cs

var mappingConfig = new MapperConfiguration(mc =>
{
 mc.AddProfile(new GemlemMapper());
 });
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);

希望它会有所帮助,还请注意,您需要使用的所有属性都应包含在 Include() 中。


推荐阅读