I ran into a problem in a project and successfully reproduced it in one test project.
I have the following dtos:
public class AppUserDto
{
public int Id { get; set; }
public string Name { get; set; }
}
public class IssueDto
{
public int Id { get; set; }
public AppUserDto Owner { get; set; }
public AppUserDto Creator { get; set; }
}
The corresponding models are exactly the same, except that there are typical relationships instead of DTO (obviously).
AutoMapper Configuration:
Mapper.CreateMap<AppUser, AppUserDto>().MaxDepth(1);
Mapper.CreateMap<Issue, IssueDto>().MaxDepth(1);
The simplest of the queries:
var i = context.Issues.ProjectTo<IssueDto>().FirstOrDefault();
This always calls a NotSupportedException
:
The type 'AppUserDto' 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.
This, of course, is a problem with automapper.
Now I have tried the following:
Mapper.CreateMap<AppUser, AppUserDto>().MaxDepth(1)
.ProjectUsing(u => new AppUserDto
{
Id = u == null ? -1 : u.Id,
Name = u == null ? null : u.Name,
});
This makes type queries context.Issues.ProjectTo<IssueDto>()...
successful. But this in turn makes direct comparisons for the AppUser
result of zero values (or 0 for Id). Therefore context.Users.ProjectTo<AppUserDto>().FirstOrDefault()
(or even Mapper.Map<AppUserDto>(context.Users.FirstOrDefault())
) always returns AppUserDto
with default values for their details.
, dto- dto, dto-?
ProjectUsing ( ) , , .
EDIT:
, , github , .