Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string.Split() in AutoMapper issue

I have an ASP .Net core application. I am simply trying to have my AutoMapper configure to convert a string comma delimited into a list of strings as per this configuration:

configuration.CreateMap<Job, JobDto>()
             .ForMember(dto => dto.Keywords, options => options.MapFrom(entity => entity.Keywords.Split(',').ToList()))

For some reason it does not get compiled and give me the following error:

An expression tree may not contain a call or invocation that uses optional argument

I can't see why I am getting this error. I am pretty sure that I have done that in my other projects before without any such error.

like image 848
Mohammad Shadmehr Avatar asked Feb 25 '19 00:02

Mohammad Shadmehr


People also ask

Does AutoMapper support .NET 5?

AutoMapper works fine in . NET 5 -- they way you inject it is broken.

Should AutoMapper be Singleton?

Your configuration (e.g. Automapper Profiles) are singletons. That is, they are only ever loaded once when your project runs. This makes sense since your configurations will not change while the application is running.

Why do we need AutoMapper in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


2 Answers

As error says, Split function has an optional parameter. The full signature of it is as this (options is optional)

public string[] Split(string separator, StringSplitOptions options = StringSplitOptions.None)

As you are trying to use a function with default value inside an expression tree, it gives you the error. To Fix it, easy, just pass on optional parameters by yourself. ( StringSplitOptions.None ) So, simply change it to this:

entity.Keywords.Split(',' , StringSplitOptions.None).ToList()
like image 172
Ali Abdoli Avatar answered Sep 19 '22 12:09

Ali Abdoli


This is completely true.

Error is raised because expression tree being created is about to contain some more complex logic, like .Split(',').ToList(), which is not an accessible property or method, only top-level reflected object properties and methods are supported (like in class MemberInfo).

Property chaining, deep-calls (.obj1property.obj2property), extension methods are not supported by the expression trees, like in this .ToList() call.

My solution was like this:

// Execute a custom function to the source and/or destination types after member mapping
configuration.CreateMap<Job, JobDto>()
  .AfterMap((dto,jobDto)=>jobDto.Keywords = dto.Keywords.Split(',').ToList());
like image 38
Artur Mustafin Avatar answered Sep 18 '22 12:09

Artur Mustafin