Skip to content

Map<TSource, TDestination> should have class constraint for TDestination #736

Open
@praschl

Description

In class TypeAdapterSetter<TSource, TDestination>, the following method

public TypeAdapterSetter<TSource, TDestination> Map<TDestinationMember, TSourceMember>(
    Expression<Func<TDestination, TDestinationMember>> member,
    Expression<Func<TSource, TSourceMember>> source,
    Expression<Func<TSource, bool>>? shouldMap = null)

and probably some more should have a "where TDestination: class" constraint.

We have an extension method that looks like this:

public static TypeAdapterSetter<Backend.Customer, TDestination> MapCustomer<TDestination>(this TypeAdapterSetter<Backend.Customer, TDestination> source)
    where TDestination : class, ICustomerData
{
    source
        .Map(dst => dst.Oid, src => src.Oid)
        // ...
        ;
}

if we remove the class constraint, the .Map() will throw the following exception:

System.ArgumentException: Allow only member access (eg. obj => obj.Child.Name) (Parameter 'lambda')
   at Mapster.Utils.ExpressionEx.GetMemberPath(LambdaExpression lambda, Boolean firstLevelOnly, Boolean noError)
   at Mapster.TypeAdapterSetter`2.Map[TDestinationMember,TSourceMember](Expression`1 member, Expression`1 source, Expression`1 shouldMap)

The Map() will work well as soon as we add the class constraint. (Mapping into structs also wouldn't make any sense, since that would only map into a copy.)

More methods might profit from the class constraint, but this is the one we had the issue with. If the method had a class constraint in the first place, we would have had to add it to our code to be able to even compile.

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