" with AutoMapper IQueryable Extension Project().To

AutoMapper IQueryable Extension throws "Unable to compare elements of type <Complex Type>" with

AutoMapper IQueryable Extension Project().To<TViewModel>().SingleOrDefault() throws this exception:

Unable to compare elements of type App.Domain.MyComplexType. Only primitive types, enumeration types, and object types are supported.

I have this model:

 public class MyEntityType // this is an entity type on the dbContext { public int Id {get;set; public MyComplexType MyComplexType {get;set;} } public class MyComplexType // this is a complex type { public decimal Property1 { get; set;} public string Property2 { get;set;} } public class ViewModel { public int Id { get;set;} public decimal MyComplexTypeProperty1 { get;set;} } 

I use AutoMapper to customize the display from IQueryable<MyEntityType> to ViewModel :

 Mapper.CreateMap<MyEntityType, MyComplexType>(); // I rely on AutoMapper //convention for flattening `source.MyComplexType.Property1` to `dest.MyComplexTypeProperty1' 

Then I try to extract one element as follows:

 var myItem = myContext.Where(x => x.Id == id).Project().To<ViewModel>().SingleOrDefault(); 

I get the exception above when SingleOrDefault() is called, so apparently

I'm currently working on this by first calling SingleOrDefault() and then doing the mapping, this works:

 var myItem = Mapper.Map<ViewModel>(myContext.Find(id)); 

Other posts mostly say that when you try to compare a complex EF type with a null value, as, for example, in the Where clause, the error above appears, but this, apparently, is not so.

+5
source share
1 answer

LINQ for entities cannot perform a comparison (null check) for complex types, as you suggested. For example, this does not work ...

 myContext.Select(i => new { MyComplexType = i.MyComplexType != null ? new MyComplexTypeViewModel() { Property1 = i.MyComplexType.Property1 } : null }) 

By default, Automapper tries to display null source values ​​as null and sometimes adds similar conditions to the generated expression when using Project().To<>() or Mapper.Engine.CreateMapExpression<,>() .

In my case, I matched the entire complex type with its own view model and did not use property alignment. This configuration value solved the problem for me ...

 Mapper.AllowNullDestinationValues = false; 

You can try to manually create an expression mapping using CreateMapExpression<TSource,TDest>() and look for null checks of a complex type to see if it has the same situation.

+4
source

All Articles