Open Closed

Object reference not set to an instance of an object in Master Child WithNavigationPropertiesTo-WithNavigationPropertiesDtoMapper #10238


User avatar
0
sekmenhuseyin created

Hi I'm trying some project types and always getting error. especially this one annoys me:https://github.com/abpframework/abp/issues/24415 I'm using abp suite 10.0.1. I've tried with different db and solution configuration but always got the same error After creating a new entity in master-child format, backend gives error while visiting page tables are not important. I've just added a name property. a master table, one with navigation and a child table

  • Exception message and full stack trace: at AbpSolution1.CompanyWithNavigationPropertiesToCompanyWithNavigationPropertiesDtoMapper.MapToListOfSectorDto(ICollection1 source) in D:\Projects\AbpSolution1\src\AbpSolution1.Application\obj\Debug\net10.0\Riok.Mapperly\Riok.Mapperly.MapperGenerator\CompanyWithNavigationPropertiesToCompanyWithNavigationPropertiesDtoMapper.g.cs:line 79 at AbpSolution1.CompanyWithNavigationPropertiesToCompanyWithNavigationPropertiesDtoMapper.MapToOrganisationDto(Organisation source) in D:\Projects\AbpSolution1\src\AbpSolution1.Application\obj\Debug\net10.0\Riok.Mapperly\Riok.Mapperly.MapperGenerator\CompanyWithNavigationPropertiesToCompanyWithNavigationPropertiesDtoMapper.g.cs:line 47 at AbpSolution1.CompanyWithNavigationPropertiesToCompanyWithNavigationPropertiesDtoMapper.Map(CompanyWithNavigationProperties source) in D:\Projects\AbpSolution1\src\AbpSolution1.Application\obj\Debug\net10.0\Riok.Mapperly\Riok.Mapperly.MapperGenerator\CompanyWithNavigationPropertiesToCompanyWithNavigationPropertiesDtoMapper.g.cs:line 12 at Volo.Abp.Mapperly.MapperlyAutoObjectMappingProvider.Map[TSource,TDestination](Object source) at lambda_method4041(Closure, Object, Object, Object) at Volo.Abp.Mapperly.MapperlyAutoObjectMappingProvider.TryToMapCollection[TSource,TDestination](TSource source, TDestination destination, TDestination& collectionResult) at Volo.Abp.Mapperly.MapperlyAutoObjectMappingProvider.Map[TSource,TDestination](Object source) at Volo.Abp.ObjectMapping.DefaultObjectMapper.AutoMap[TSource,TDestination](Object source) at Volo.Abp.ObjectMapping.DefaultObjectMapper.Map[TSource,TDestination](TSource source) at AbpSolution1.Companies.CompaniesAppServiceBase.GetListAsync(GetCompaniesInput input) in D:\Projects\AbpSolution1\src\AbpSolution1.Application\Companies\CompaniesAppService.cs:line 38 at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.Authorization.AuthorizationInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.GlobalFeatures.GlobalFeatureInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.Auditing.AuditingInterceptor.ProceedByLoggingAsync(IAbpMethodInvocation invocation, AbpAuditingOptions options, IAuditingHelper auditingHelper, IAuditLogScope auditLogScope) at Volo.Abp.Auditing.AuditingInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.Validation.ValidationInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.Uow.UnitOfWorkInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at lambda_method3933(Closure, Object) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.

  • Steps to reproduce the issue:

solution config:

  • Template: app
  • Created ABP Studio Version: 2.1.3
  • Current ABP Studio Version: 2.1.3
  • Tiered: Yes
  • Multi-Tenancy: Yes
  • UI Framework: angular
  • Theme: leptonx
  • Theme Style: system
  • Theme Menu Placement: side
  • Run Install Libs: No
  • Progressive Web App: No
  • Run Progressive Web App Support: No
  • Database Provider: ef
  • Database Management System: sqlite
  • Separate Tenant Schema: Yes
  • Mobile Framework: none
  • Public Website: No
  • Social Login: No
  • Include Tests: Yes
  • Kubernetes Configuration: No
  • Distributed Event Bus: none
  • Use Local References: No
  • Optional Modules:
    • GDPR
    • TextTemplateManagement
    • LanguageManagement
    • AuditLogging
    • OpenIddictAdmin
  • Selected Languages: English, Turkish
  • Default Language: English
  • Create Command: abp new AbpSolution1 -t app --tiered --ui-framework angular --database-provider ef --database-management-system sqlite --theme leptonx --separate-tenant-schema --skip-migration --skip-migrator --without-cms-kit --dont-run-install-libs --dont-run-bundling --no-social-logins -no-file-management

1 Answer(s)
  • User Avatar
    0
    AI-Bot created
    Support Team ABP Agent
    1. Solution
    • Root cause: In ABP v10 projects generated by ABP Suite, Mapperly generates a mapper class like CompanyWithNavigationPropertiesToCompanyWithNavigationPropertiesDtoMapper.g.cs. The NullReferenceException typically occurs when a navigation collection or reference (e.g., Sectors, Child collection, or a WithNavigationProperties reference) is null and the generated MapToListOf... or MapTo... method doesn’t guard against null. This happens if the repository/service returns entities without including related data or returns null collections, and the generated mapper directly enumerates them.

    • Fix it at the query layer (recommended): Ensure navigation properties and collections are loaded (Include / ThenInclude) before mapping. In the repository GetListWithNavigationPropertiesAsync (or the query used by your AppService), include the related entities/collections and coalesce collections to empty lists where needed.

      Example:

    public async Task<List<CompanyWithNavigationProperties>> GetListWithNavigationPropertiesAsync(
          string filterText, string sorting, int maxResultCount, int skipCount, CancellationToken cancellationToken = default)
      {
          var query = (await GetQueryableAsync())
              .Include(x => x.Organisation)              // reference
              .Include(x => x.Sectors)                   // collection
              .AsSplitQuery();                           // optional for safety
    
          // apply filters, sorting, paging...
    
          var items = await query
              .OrderBy(string.IsNullOrWhiteSpace(sorting) ? nameof(Company.Name) : sorting)
              .Skip(skipCount)
              .Take(maxResultCount)
              .ToListAsync(GetCancellationToken(cancellationToken));
    
          // Optional: defensive normalization so Mapperly doesn't hit null collections
          foreach (var item in items)
          {
              item.Sectors ??= new List<Sector>();
          }
    
          return items.Select(e => new CompanyWithNavigationProperties
          {
              Company = e,
              Organisation = e.Organisation,
              Sectors = e.Sectors
          }).ToList();
      }
    
    • If you have a custom WithNavigationProperties type (e.g., CompanyWithNavigationProperties wrapping master + refs): Make sure that when constructing this wrapper, you never pass null collections. Always set empty lists when data is missing:
    return new CompanyWithNavigationProperties
      {
          Company = company,
          Organisation = company.Organisation,
          Sectors = company.Sectors ?? new List<Sector>()
      };
    
    • Optionally harden the generated partial mapper (non-breaking approach): Mapperly allows partial methods. Create a partial class with the same name and add safe wrappers to coalesce collections before mapping.
    // In Application project (not in obj folder)
      public partial class CompanyWithNavigationPropertiesToCompanyWithNavigationPropertiesDtoMapper
      {
          private ICollection<Sector> Safe(ICollection<Sector>? source) => source ?? Array.Empty<Sector>();
    
          // If your generated method is MapToListOfSectorDto, add a partial wrapper where you call it with Safe(...)
          public CompanyWithNavigationPropertiesDto MapSafe(CompanyWithNavigationProperties source)
          {
              // normalize before calling generated Map(...)
              source.Sectors ??= new List<Sector>();
              return Map(source); // calls the generated method
          }
      }
    

    Then use ObjectMapper.Map with the safe entry point (or normalize source prior to mapping). Prefer fixing data loading as shown above.

    • Ensure object-to-object mapping integration is properly configured for v10 (Mapperly): ABP v10 uses Mapperly by default. Make sure:
      • Volo.Abp.Mapperly package is referenced by your Application layer.
      • Your module depends on AbpMapperlyModule:
    [DependsOn(typeof(AbpDddApplicationModule), typeof(AbpAutoMapperModule), typeof(AbpMapperlyModule))]
        public class YourApplicationModule : AbpModule
        {
        }
    

    This guarantees ABP’s MapperlyAutoObjectMappingProvider is active.

    • Verify AppService mapping usage: In your AppService GetListAsync, continue using ObjectMapper.Map on the already-normalized source:
    public override async Task<PagedResultDto<CompanyWithNavigationPropertiesDto>> GetListAsync(GetCompaniesInput input)
      {
          var items = await _companyRepository.GetListWithNavigationPropertiesAsync(
              input.FilterText, input.Sorting, input.MaxResultCount, input.SkipCount);
    
          // items must have non-null navigation collections
          var dtos = ObjectMapper.Map<List<CompanyWithNavigationProperties>, List<CompanyWithNavigationPropertiesDto>>(items);
    
          var totalCount = await _companyRepository.GetCountAsync(input.FilterText /* ... */);
    
          return new PagedResultDto<CompanyWithNavigationPropertiesDto>(totalCount, dtos);
      }
    
    • Why this works: Mapperly’s generated methods typically enumerate the source collections. If EF Core did not load the navigation properties or they’re null, enumerating causes NullReferenceException. Loading relations via Include and normalizing to empty collections prevents that.
    1. Sources
    • Object-to-Object Mapping in ABP: https://docs.abp.io/en/abp/latest/Object-To-Object-Mapping
    • ABP Module system (for module dependencies like AbpMapperlyModule): https://abp.io/docs/latest/framework/architecture/modularity/basics
    • ABP Suite master–detail generation overview: https://abp.io/docs/latest/suite/creating-master-detail-relationship

    This response was generated by AI. If it didn’t solve your problem, feel free to post a new answer — our support team will jump in to help you soon.

Boost Your Development
ABP Live Training
Packages
See Trainings
Mastering ABP Framework Book
The Official Guide
Mastering
ABP Framework
Learn More
Mastering ABP Framework Book
Made with ❤️ on ABP v10.1.0-preview. Updated on December 17, 2025, 07:08
1
ABP Assistant
🔐 You need to be logged in to use the chatbot. Please log in first.