"-6ren"> "-AutoMapper IQueryable 扩展的 Project().To().SingleOrDefault()抛出这个异常: Cannot compare elements of type 'A-6ren">
gpt4 book ai didi

c# - AutoMapper IQueryable Extension 抛出 "Cannot compare elements of type "

转载 作者:太空狗 更新时间:2023-10-29 23:21:50 28 4
gpt4 key购买 nike

AutoMapper IQueryable 扩展的 Project().To<TViewModel>().SingleOrDefault()抛出这个异常:

Cannot compare elements of type 'App.Domain.MyComplexType. Only primitive types, enumeration types and entity types are supported.

我有这个模型:

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;}
}

我使用 AutoMapper 配置来自 IQueryable<MyEntityType> 的映射至 ViewModel :

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

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

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

我在 SingleOrDefault() 时得到上述异常被称为,所以显然

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

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

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

最佳答案

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

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

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

在我的例子中,我将整个复杂类型映射到它自己的 View 模型并且没有使用属性展平。这个配置值为我解决了这个问题......

Mapper.AllowNullDestinationValues = false;

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

关于c# - AutoMapper IQueryable Extension 抛出 "Cannot compare elements of type <Complex Type>",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30197233/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com