Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ProjectTo does not recognize parameterless constructor

I have a class for getting data from DB, which looks like this (some field are missing for keeping it simple):

public class BranchDetailDto
{
    public BranchDetailDto()
    {
    }

    public BranchDetailDto(int supplierId, string supplierName)
    {
        SupplierId = supplierId;
        SupplierName = supplierName;
    }

    public int Id { get; set; }

    public int SupplierId { get; set; }

    public string SupplierName { get; set; }
}

Then I want to retrieve data in a query and use ProjectTo extension method of AutoMapper for it:

return await _context.Branches
            .Where(b => b.Id == message.Id)
            .ProjectTo<BranchDetailDto>(_configuration)
            .SingleAsync();

However, this operation throws error and error page says:

NotSupportedException: Only parameterless constructors and initializers are supported in LINQ to Entities.

Why? My class does have a parameterless constructor. Is it possible that AutoMapper does not see it? Or does it want just ONE constructor in the definition and the second one is making troubles? It sounds strange to me.

EDIT

Automapper version is 6.1.1, Automapper.EF6 is 1.0.0. There's nothing special in configuration, regarding this type, the map should be created automatically as all the fields are mappable by naming convention (of course, CreateMissingTypeMaps in cfg is set to true).

However, I've commented the second constructor with parameters and it has started to work. So it's really somehow confused with the second constructor, but I believe it's not an intended behaviour (to be able to have just one constructor in a class).

like image 304
M. Pipal Avatar asked Nov 17 '25 22:11

M. Pipal


1 Answers

By default AM uses constructor mapping when possible, so in your case it tries to use the DTO constructor with parameters, which is not supported by EF.

To fix the issue, either disable the constructor mapping globally (as mentioned in the link):

cfg.DisableConstructorMapping();
cfg.CreateMap<BranchDetail, BranchDetailDto>();

or use ConstructProjectionUsing method to let AM use the parameterless constructor during projection to target DTO:

cfg.CreateMap<BranchDetail, BranchDetailDto>()
    .ConstructProjectionUsing(src => new BranchDetailDto());
like image 189
Ivan Stoev Avatar answered Nov 19 '25 10:11

Ivan Stoev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!