Skip to content

BUG: Projection mapping bug when a non-PK property is called Id #231

@jornhd

Description

@jornhd

Using .NET 7.0, AgileMapper 1.8.1, EF Core 7.0.1
I have an entity class (code-first) called Document that has a primary key DocumentId (int) and a property Id (string).

public class Document
{
    public string DocumentId { get; set; }
    public string Id { get; set; }
    public string Description { get; set; }
    public DateTime CreatedDate { get; set; }
}

With code-first I had to add entity.HasKey(x => x.DocumentId); to make DocumentId PK, else it defaulted to Id as PK.
I also have a DocumentDto without DocumentId, only Id.

public class DocumentDto
{
    public string Id { get; set; }
    public string Description { get; set; }
    public DateTime CreatedDate { get; set; }
}

But when running a query projecting to DocumentDto, I notice that the Id in the dto is getting the value from DocumentId!
I tried to correct this by creating an explicit mapping in a MappingConfiguration class, but then I got an exception telling me that the mapping was unnecessary.
I logged the generated query, and here it is converting DocumentId AS Id!

SELECT CONVERT(varchar(11), [d].[DocumentId]) AS [Id], [d].[Description], [d].[CreatedDate]
FROM [Document] AS [d]

Why is it doing this? This must be a bug!

However, I've managed to workaround this by having this mapping in the Project().To() config:

    .Project()
    .To<DocumentDto>(cfg =>
        cfg.WhenMapping.From<Document>()
            .ProjectedTo<DocumentDto>()
            .Map(src => src.Id)
            .To(dst => dst.Id))

With this, the query becomes as expected

SELECT [d].[Id], [d].[Description], [d].[CreatedDate]
FROM [Document] AS [d]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions