首页 > 解决方案 > 嵌套实体中的自动映射器问题

问题描述

实体:

public class AccountEntity: MasterEntity
     {
    
    public AccountType AccountType { get; set; }
    public DepartmentEntity Department { get; set; }
    public string LeadSource { get; set; }
    public ResourceEntity AccountManager { get; set; }
    public AccountQualificationStatus QualificationStatus { get; set; }
  }

  public class DepartmentEntity : MasterEntity
  {
  }
   public class ResourceEntity : MasterEntity
    {
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    }
   public abstract class MasterEntity: Entity
  {
    public string Name { get; set; }
    public string Code { get; set; }
   }

 Model

 public class Accounts
   {
    private string depname;
    public int Id { get; set; }
    public string Name { get; set; }
    public int Code { get; set; }
    public string AccountType { get; set; }
    public string Department { get; set; }
   }
    public AccountMappingProfile()
    {
        CreateMap<Account, AccountTest>().ReverseMap();
        CreateMap<Opportunity, OpportunityEntity>().ReverseMap();
        CreateMap<Accounts, AccountEntity>().ReverseMap();
        CreateMap<Resource, ResourceEntity>().ReverseMap();
        CreateMap<Projects, ProjectEntity>().ReverseMap();
        
    }

       public static class AccountMapper
     {
       private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() =>
      {
           var config = new MapperConfiguration(cfg => {

            cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
            cfg.AddProfile<AccountMappingProfile>();
        });
        var mapper = config.CreateMapper();
        return mapper;
    });

      public static IMapper Mapper => Lazy.Value;
   }

我能够获取资源详细信息。当我使用部门和资源获取帐户时,部门的值在自动映射后给我 null。

    public async Task<IEnumerable<Accounts>> GetAccounts()
    {
        try
        {
        var accounts = await _context.Account.Include(c=>c.Director).ToListAsync();
            
           // accounts = await _context.Account.Include(c => c.Department).ToListAsync();

    return AccountMapper.Mapper.Map<List<Accounts>>(accounts);
  }
         }

控制器方法:

   public async Task<IEnumerable<Accounts>> GetClients()
    {
        var result = await _repository.GetAccounts();
        return result;
    }

如果我取消注释代码以包含部门,则它正在给出对象名称。我还需要获取部门详细信息。我怎样才能得到那个。部门实体正在继承主实体。

标签: model-view-controllernestedentity-framework-corelinq-to-entitiesautomapper

解决方案


推荐阅读