AutoMapper IQueryable Extension抛出"无法比较<Complex Type>类型的元素"

Aun*_*Aun 5 c# entity-framework automapper

AutoMapper IQueryable Extension's Project().To<TViewModel>().SingleOrDefault()抛出此异常:

无法比较'App.Domain.MyComplexType类型的元素.仅支持基本类型,枚举类型和实体类型.

我有这个型号:

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;}
}
Run Code Online (Sandbox Code Playgroud)

我使用AutoMapper配置映射IQueryable<MyEntityType>ViewModel:

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

然后我尝试检索这样的单个项目:

var myItem = myContext.Where(x => x.Id == id).Project().To<ViewModel>().SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)

SingleOrDefault()被调用时,我得到了上述异常,显然

我目前通过首先调用SingleOrDefault()然后进行映射来解决这个问题,这有效:

var myItem = Mapper.Map<ViewModel>(myContext.Find(id));
Run Code Online (Sandbox Code Playgroud)

其他帖子基本上说当尝试将EF复杂类型与null进行比较时出现上述错误,例如,在Where子句中,但这显然不是这里的情况.

Tom*_*zal 6

LINQ to entity 无法按照您的建议对复杂类型执行比较(空检查)。例如,这不起作用......

myContext.Select(i => new
{
    MyComplexType = i.MyComplexType != null ? 
        new MyComplexTypeViewModel() 
        {  
           Property1 = i.MyComplexType.Property1
        }
        : null
})
Run Code Online (Sandbox Code Playgroud)

默认情况下,Automapper 尝试将空源值映射为空值,有时在使用Project().To<>()或时在生成的表达式中添加类似的条件Mapper.Engine.CreateMapExpression<,>()

在我的情况下,我将整个复杂类型映射到它自己的视图模型并且没有使用属性扁平化。这个配置值为我解决了这个问题......

Mapper.AllowNullDestinationValues = false;
Run Code Online (Sandbox Code Playgroud)

您可以尝试使用手动创建映射表达式,CreateMapExpression<TSource,TDest>()并在复杂类型上查找空值检查以查看情况是否相同。