Can I force Automapper to initialise properties in

2019-09-14 16:36发布

问题:

I'm using Automapper and the Queryable Extensions to project some (similar) models into the same DTO in order to concatenate and sort them for paging on the DB server (via Entity Framework) without returning the data until it is paged.

        var tasksType1 = context.TasksType1.Project().To<MyDto>();
        var tasksType2 = context.TasksType2.Project().To<MyDto>();
        var allTasks = tasksType1.Concat(tasksType2);
        return allTasks.ToMyPagedList()

This works well, except that now my models have got slightly more complex, Automapper seems to initialise the projection in a slightly different order each time which results in the error:

The type 'AngularJSAuthentication.API.Dtos.ActivityDashboard.ActivityDashboardDto2' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.

Is there any way of forcing Automapper to initialise the projection in a controllable manner? I have already set up the maps to define every property using .ForMember and .MapFrom in exactly the same order for both types but even that doesn't seem to do it, and looking at the SQL which is created, it doesn't seem to have anything to do with the property order in the initial model either.

Any suggestions gratefully received!

回答1:

I'd modify this query to concat the two together, then apply projections:

    var tasksType1 = context.TasksType1;
    var tasksType2 = context.TasksType2;
    var allTasks = tasksType1.Concat(tasksType2);
    return allTasks.ProjectTo<MyDto>().ToMyPagedList()

The LINQ provider likely can't handle the complexity of a projection then a concatenation, but might be able to handle the reverse.

In general with AutoMapper I try to have projection be the very last step in the process.