mapperly icon indicating copy to clipboard operation
mapperly copied to clipboard

Lambda expression variable issue with `x` when comparing to source

Open bradmarder opened this issue 1 month ago • 2 comments

The following code works as expected.

public record Blog(List<Post> Posts);
public record Post(int Id);
public record BlogDto(int Id);

[Mapper(RequiredMappingStrategy = RequiredMappingStrategy.Target)]
public static partial class BlogMapper
{
	public static partial IQueryable<BlogDto> ProjectToDto(this IQueryable<Blog> q);

	[MapPropertyFromSource(nameof(BlogDto.Id), Use = nameof(MapId))]
	public static partial BlogDto BlogMap(Blog blog);

	private static int MapId(Blog blog) => blog.Posts.Count(TEST => TEST.Id == blog.Posts.Count);
}

Will generate the following snippet.

        return global::System.Linq.Queryable.Select(
            q,
            x => new global::BlogDto(
                global::System.Linq.Enumerable.Count(x.Posts, TEST => TEST.Id == x.Posts.Count)
            )
        );

However if you modify the MapId method to use an x for the lambda variable, you get an incorrect mapping.

private static int MapId(Blog blog) => blog.Posts.Count(x => x.Id == blog.Posts.Count);

        return global::System.Linq.Queryable.Select(
            q,
            x => new global::BlogDto(
                global::System.Linq.Enumerable.Count(x.Posts, x => x.Id == x.Posts.Count)
            )
        );

This is not a contrived example, but an actual issue I ran into. Maybe instead of the generator defaulting to x for the queryable select, use something more unique?

bradmarder avatar Nov 01 '25 02:11 bradmarder

Hey, @latonz , I looked into this myself, too. I created a solution: https://github.com/faddiv/mapperly/tree/bugfix/fix-name-collision-on-inlined-mapping, but then I realized something, somewhere, kind of handled this situation, since one of the integration tests changed in an unintended way. Basically, an x got reserved twice. I haven't looked into this yet, but if you are interested in my solution, I would continue.

faddiv avatar Nov 25 '25 15:11 faddiv

Ok, I looked into it, the integration test change had a good reason, so I will open the PR.

faddiv avatar Nov 25 '25 19:11 faddiv