Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
praschl opened this issue Nov 19, 2024 · 0 comments
Open

Comments

@praschl
Copy link

praschl commented Nov 19, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant