Skip to content

ProjectToType throws when nullable navigation maps to record DTO with non-nullable value type #898

@unzeitip

Description

@unzeitip

First of all, thank you for Mapster — it's been a great fit for our project and we really appreciate the work you've put into it.

I've run into what looks like a bug with ProjectToType when mapping a nullable navigation property to a record DTO that has non-nullable value type parameters. Here I provide additional context if it helps track this down.

Mapster version: 10.0.6
EF Core version: 10.0.5

Minimal reproduce

// Entities:
public class OrderEntity
{
    public int Id { get; set; }
    public int? CodId { get; set; }
    public OrderCodEntity? Cod { get; set; }
}

public class OrderCodEntity
{
    public int Id { get; set; }
    public long Value { get; set; }
}

// DTOs:
public record OrderDto(int Id, OrderCodDto? Cod);
public record OrderCodDto(long Value);

// Mapping + query:
TypeAdapterConfig<OrderEntity, OrderDto>.NewConfig();
TypeAdapterConfig<OrderCodEntity, OrderCodDto>.NewConfig();

var results = dbContext.Orders
    .ProjectToType<OrderDto>()
    .ToList();  // throws when any Order has Cod == null

// Seed data:
new OrderEntity { Id = 1, Cod = new OrderCodEntity { Value = 42L } }  // OK
new OrderEntity { Id = 2, Cod = null }                               // causes crash

Expected behavior

OrderDto(1, OrderCodDto(42))
OrderDto(2, null)

Actual behavior

System.InvalidOperationException: Nullable object must have a value.

Workaround

   .Map(
       d => d.Cod,
       s => s.Cod == null ? null : new OrderCodDto(s.Cod.Value)
   );

Note

The issue persists when using Mapster.EFCore 10.0.6 and calling EFCoreProjectToType<OrderDto>() instead of ProjectToType<OrderDto>() - same exception is thrown.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions