I keep getting "needs to have a constructor with 0 args or only optional args. (Parameter 'type')"

15.2k views Asked by At

I am using version 9. I am using a Profile based configuration. When I run the application the Mapper.Map<>() method throws the following exception:

JobAssist.Services.ResumeBankMgmt.API.Application.ViewModels.ResumeBankViewModel needs to have a constructor with 0 args or only optional args. (Parameter 'type')

I don't know what is causing this.

4

There are 4 answers

2
Pierre On BEST ANSWER

Classic mapping works for mapping based on source members: https://docs.automapper.org/en/latest/Construction.html

If you cannot change the class (in contracts for example) having constructors with parameters that are different from members, you can use ConstructUsing.

You can use it like this to specify arguments :

Mapper.CreateMap<ObjectFrom, ObjectTo>()
    .ConstructUsing(x => new ObjectTo(arg0, arg1, etc));

Check the full answer here: Automapper - how to map to constructor parameters instead of property setters

1
rfmodulator On

Assuming you have access to the source code, and this isn't in a 3rd party assembly you're referencing...

Find the definition of the class ResumeBankViewModel (ViewModels\ResumeBankViewModel.cs is probably a good place to start.)

And add this line:

public ResumeBankViewModel(){ }

If there is a line like this:

private ResumeBankViewModel() /* { etc. } */

Or this:

internal ResumeBankViewModel() /* { etc. } */

You might change the private/internal to public.

You may also wish to look at the other public constructors that are already defined and pass some appropriate values to one of them:

public ResumeBankViewModel() : this(value1, value2, value3) { }

Or make it's parameters optional:

public ResumeBankViewModel(object arg1 = value1, object arg2 = value2, object arg3 = value3)

Any of these might lead to more issues that you will need to work through, but one of these is the bare minimum to clear this error.

0
Mike Lenart On

The issue was that I had one parameter that was not named exactly like my class property. See I changed categories in constructor to resumeCategories.

Original code:

public class ResumeBankViewModel
{
    public List<ResumeCategoryViewModel> ResumeCategories { get; set; }
    
    public ResumeBankViewModel(int id, int jobSeekerID, List<ResumeViewModel> resumes, List<ResumeCategoryViewModel> categories)
}

new code:

public class ResumeBankViewModel
{
    public List<ResumeCategoryViewModel> ResumeCategories { get; set; }

    public ResumeBankViewModel(int id, int jobSeekerID, List<ResumeViewModel> resumes, List<ResumeCategoryViewModel> resumeCategories)
}
0
jrn6270 On

I got the this error when using a "wrong" access modifier, i.e. internal instead of public, when mapping between two classes.