【发布时间】:2021-12-05 16:26:44
【问题描述】:
看起来很简单,但我无法使用 EF 核心执行以下查询。
public class ParentThing // EF entity
{
public int Id { get; set; }
public string Name { get; set; }
public int? ChildThingId { get; set; }
public ChildThing Child { get; set ; }
}
public class ChildThing // EF entity
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ChildDTO
{
public int Id { get; set; }
}
public class ParentDTO
{
public string Name { get; set; }
public ChildDTO Child { get; set; }
}
public static void Run(int id, DbSet<ParentThing> dbSet, IMapper mapper)
{
// mappings are something like this...
// CreateMap<ChildThing, ChildDTO>();
// CreateMap<ParentThing, ParentDTO>();
var dtos = mapper.ProjectTo<ParentDTO>(dbSet)
.Where(e => e.Child.Id == id) // this throws an exception
.ToList();
}
尝试执行查询时出现以下异常。
System.InvalidOperationException: The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'.
我尝试将查询到的 id 转换为可为空的 int 并得到以下异常。
System.InvalidOperationException: Rewriting child expression from type 'System.Int32' to type 'System.Nullable`1[System.Int32]' is not allowed, because it would change the meaning of the operation. If this is intentional, override 'VisitUnary' and change it to allow this rewrite.
我真的需要展平嵌套属性才能查询它们吗?
【问题讨论】:
-
尝试更新 EF Core。过滤器也必须在
ProjectTo之前。 -
你试过这个吗.Where(e => e.Child!=null && e.Child.Id == id)
-
首先检查空对象仍然会引发异常:System.InvalidOperationException:不允许将子表达式从“System.Int32”类型重写为“System.Nullable`1[System.Int32]”类型,因为它会改变操作的含义。如果这是故意的,请覆盖“VisitUnary”并将其更改为允许此重写。
-
在调用 ProjectTo 之前过滤 dbSet 似乎确实有效,尽管感觉有点笨拙。我将看看底层的查询字符串,看看它有多复杂。
-
您是否在没有映射的情况下尝试了相同的查询?它可以帮助找到异常源
标签: c# entity-framework-core automapper