AgileMapper icon indicating copy to clipboard operation
AgileMapper copied to clipboard

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

Open jornhd opened this issue 2 years ago • 0 comments

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]

jornhd avatar Jan 26 '23 12:01 jornhd