Paul Carlton
Paul Carlton

Reputation: 2993

Automapper projection returns empty list when query is not empty

I'm implementing automapper for view models in a project and I'm just getting started with it. A hurdle I'm finding myself up against is a type of behavior I'm not familiar with in Automapper. I've been using automapper on a couple projects now and I haven't come across this issue before.

Basically in code this is what's happening:

var q = dbContext.Orders.Where(x => x.Name == 'name');
var l = q.ToList(); // count == 10
var shared = q.ProjectTo<OrderSharedModel>().ToList(); // count == 0

I figured out that when mapping a property that's null, it doesn't map anymore and it's like it just skips the mapping of that entity entirely.

For example:

class Order {
  public int OrderId { get; set; }
  public string Name { get; set; }
  public int? OrderTypeId { get; set; }
  public virtual OrderType { get; set; }
}

class OrderSharedModel {
  public int OrderId { get; set; }
  public string Name { get; set; }
  public OrderTypeSharedModel OrderType { get; set; }
}

If OrderType is null in Order then it will cause ProjectTo<OrderSharedModel>().ToList() to return an empty list. If I commented out OrderType in the shared model, ProjectTo<OrderSharedModel>().ToList() will return the full list. This is weird to me.

Why would ProjectTo<OrderSharedModel>().ToList() return an empty list if the original query before ProjectTo() is not empty? Why won't automapper map a null property as null rather than skip the mapping entirely and return an empty list?

--UPDATE--

However if I use the other way mapping:

var l = q.ToList();
var sm = Mapper.Map<List<Order>, List<OrderSharedModel>>(l);

It works great. I'm doing this for now until I find exactly why the queryable extension breaks.

Upvotes: 3

Views: 1277

Answers (1)

kurdemol94
kurdemol94

Reputation: 604

Just encountered the same issue, an inner property of the dto was null and for some reason it was not in the result list. I upgraded from AutoMapper 8.1 to 9.0 and it works fine now.

Upvotes: 2

Related Questions