AutoMapper/AutoMapper.Extensions.ExpressionMapping

ArgumentException when using Select<TEnitity> on UseAsDataSource(...).For<TEnitity>()

4E-69-63-6B-20-42-6F-73 opened this issue · 4 comments

When using Select on UseAsDataSource(...).For() it will lead to an ArgumentException.

Failing unittest:

using System.Collections.Generic;
using System.Linq;
using Shouldly;
using Xunit;

namespace AutoMapper.Extensions.ExpressionMapping.UnitTests
{
    public class UseAsDataSourceWithException
    {
        [Fact]
        public void UseAsDataSourceWithSelectWillGiveAnException()
        {
            // Arrange
            var mapper = CreateMapper();

            var models = ModelBuilder.CreateListOf(10);
            var queryable = models.AsQueryable();

            // Act
            var query = queryable.UseAsDataSource(mapper)
                .For<ModelEntity>()
                .Select(x => new ModelEntity { Value = x.Value });

            var result = query.ToList();

            // Assert
            result.ShouldNotBeNull();
            result.Count.ShouldBe(10);
        }

        private static IMapper CreateMapper() =>
            new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Model, ModelEntity>();
            }).CreateMapper();

        internal class Model
        {
            public int Value { get; set; }
        }

        internal class ModelEntity
        {
            public int Value { get; set; }
        }

        internal static class ModelBuilder
        {
            internal static IEnumerable<Model> CreateListOf(int count)
            {
                for (int i = 0; i < count; i++)
                {
                    yield return new Model
                    {
                        Value = i,
                    };
                }
            }
        }
    }
}

The function GetConvertedMethodCall sets the return type of the Select clause as T instead of TEntity.
I think that in the GetConvertedMethodCall there should be an check if an input expression has an NewExpression, if it is, than it schould not convert the type.

If that is the solution, I can make a PR with the changes.

Incidentally we're just added new logic to map NewExpression in the expression mapper (not used by UseAsDataSource()).

Either fix is fine. Your recommendation works too.

Can you give me permission to create a branch?
I'm getting a 403 when I try to push my local branch to remote.

You should fork the repo and push to your fork. Then create the PR from a fork.

Closing since I have found a better way of doing it,
I'm mapping the expression and execute it on EFCore