Skip to content

Lambda expression variable issue with x when comparing to source #2012

Description

@bradmarder

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?

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions