EF6 Automapper继承/抽象类错误



我正在使用带有AutoMapper的Entity Framework 6构建一个.NET Web API,以将实体映射到DTO。当我试图引入一个带有抽象基类的TPH(每层次表)时,我会得到一个非常长而且非常无用的错误(至少对我来说)。错误如下,我不确定实际的错误是什么。我试过在谷歌上搜索它的各个部分,但都没有结果。

这是我的地图:

Mapper.CreateMap<ParentClass, ParentClassDTO>()
.Include<ClassA, ClassADTO>()
.Include<ClassB, ClassBDTO>();
Mapper.CreateMap<ClassA, ClassADTO>();
Mapper.CreateMap<ClassB, ClassBDTO>();

如果我从ParentClass中删除abstract,错误就会消失,但AutoMapper不使用子DTO类,它只使用ParentClassDTO。如果将映射全部移除,并通过API返回实体,则不会出现任何错误,并且一切正常。

我甚至不知道从哪里开始下面的错误,如何开始调试它(在调试模式下运行的web API仍然只是将这个错误输出到屏幕),或者是什么导致了这个错误。我已经尽可能简化了代码,并尝试了其他各种方法,但似乎无法解决这个问题。

这个特定的映射是另一个DTO类中的一个集合,我正在创建它以从Web API返回IQueryable<AnotherClassDTO>

return db.AnotherClass.Project().To<AnotherClassDTO>();

AnotherClassDTO(一个包含抽象集合的独立类)的设置如下:

public class AnotherClassDTO
{
public IEnumerable<ParentClassDTO> Elements;
}

错误消息:

> {"message":"An error has occurred.","exceptionMessage":"The
> 'ObjectContent`1' type failed to serialize the response body for
> content type 'text/html;
> charset=utf-8'.","exceptionType":"System.InvalidOperationException","stackTrace":null,"innerException":{"message":"An
> error has occurred.","exceptionMessage":"Exception has been thrown by
> the target of an
> invocation.","exceptionType":"System.Reflection.TargetInvocationException","stackTrace":"
> at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
> arguments, Signature sig, Boolean constructor)rn at
> System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
> Object[] parameters, Object[] arguments)rn at
> System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
> invokeAttr, Binder binder, Object[] parameters, CultureInfo
> culture)rn at System.Reflection.MethodBase.Invoke(Object obj,
> Object[] parameters)rn at
> System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslateColumnMap(Translator
> translator, Type elementType, ColumnMap columnMap, MetadataWorkspace
> workspace, SpanIndex spanIndex, MergeOption mergeOption, Boolean
> streaming, Boolean valueLayer)rn at
> System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext
> context, DbQueryCommandTree tree, Type elementType, MergeOption
> mergeOption, Boolean streaming, Span span, IEnumerable`1
> compiledQueryParameters, AliasGenerator aliasGenerator)rn at
> System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1
> forMergeOption)rn at
> System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.b__6()rn
> at
> System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1
> func, IDbExecutionStrategy executionStrategy, Boolean
> startLocalTransaction, Boolean releaseConnectionOnSuccess)rn at
> System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.b__5()rn
> at
> System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1
> operation)rn at
> System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1
> forMergeOption)rn at
> System.Data.Entity.Core.Objects.ObjectQuery`1..GetEnumerator>b__0()rn
> at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()rn at
> Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter
> writer, IEnumerable values, JsonArrayContract contract, JsonProperty
> member, JsonContainerContract collectionContract, JsonProperty
> containerProperty)rn at
> Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
> writer, Object value, JsonContract valueContract, JsonProperty member,
> JsonContainerContract containerContract, JsonProperty
> containerProperty)rn at
> Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter
> jsonWriter, Object value, Type objectType)rn at
> Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter
> jsonWriter, Object value, Type objectType)rn at
> Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object
> value)rn at
> System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type
> type, Object value, Stream writeStream, Encoding
> effectiveEncoding)rn at
> System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type
> type, Object value, Stream writeStream, Encoding
> effectiveEncoding)rn at
> System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type
> type, Object value, Stream writeStream, HttpContent content)rn at
> System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type
> type, Object value, Stream writeStream, HttpContent content,
> TransportContext transportContext, CancellationToken
> cancellationToken)rn--- End of stack trace from previous location
> where exception was thrown ---rn at
> System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)rn at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)rn at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()rn at
> System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()","innerException":{"message":"An
> error has occurred.","exceptionMessage":"Exception has been thrown by
> the target of an
> invocation.","exceptionType":"System.Reflection.TargetInvocationException","stackTrace":"
> at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
> arguments, Signature sig, Boolean constructor)rn at
> System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags
> invokeAttr, Binder binder, Object[] parameters, CultureInfo
> culture)rn at System.RuntimeType.CreateInstanceImpl(BindingFlags
> bindingAttr, Binder binder, Object[] args, CultureInfo culture,
> Object[] activationAttributes, StackCrawlMark& stackMark)rn at
> System.Activator.CreateInstance(Type type, BindingFlags bindingAttr,
> Binder binder, Object[] args, CultureInfo culture, Object[]
> activationAttributes)rn at System.Activator.CreateInstance(Type
> type, Object[] args)rn at
> System.Data.Entity.Core.Common.Internal.Materialization.CoordinatorScratchpad.Compile()rn
> at
> System.Data.Entity.Core.Common.Internal.Materialization.CoordinatorScratchpad.Compile()rn
> at
> System.Data.Entity.Core.Common.Internal.Materialization.CoordinatorScratchpad.Compile()rn
> at
> System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslateColumnMap[T](ColumnMap
> columnMap, MetadataWorkspace workspace, SpanIndex spanIndex,
> MergeOption mergeOption, Boolean streaming, Boolean
> valueLayer)","innerException":{"message":"An error has
> occurred.","exceptionMessage":"Instances of abstract classes cannot be
> created.","exceptionType":"System.InvalidOperationException","stackTrace":"
> at
> System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(IRuntimeMethodInfo
> method)rn at
> System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType,
> Object target)rn at
> System.Linq.Expressions.Compiler.LambdaCompiler.CreateDelegate()rn
> at
> System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression
> lambda, DebugInfoGenerator debugInfoGenerator)rn at
> System.Linq.Expressions.Expression`1.Compile()rn at
> System.Data.Entity.Core.Common.Internal.Materialization.CoordinatorFactory`1..ctor(Int32
> depth, Int32 stateSlot, Expression`1 hasData, Expression`1 setKeys,
> Expression`1 checkKeys, CoordinatorFactory[] nestedCoordinators,
> Expression`1 element, Expression`1 wrappedElement, Expression`1
> elementWithErrorHandling, Expression`1 initializeCollection,
> RecordStateFactory[] recordStateFactories)rn at
> System.Data.Entity.Core.Common.Internal.Materialization.CoordinatorFactory`1..ctor(Int32
> depth, Int32 stateSlot, Expression hasData, Expression setKeys,
> Expression checkKeys, CoordinatorFactory[] nestedCoordinators,
> Expression element, Expression elementWithErrorHandling, Expression
> initializeCollection, RecordStateFactory[] recordStateFactories)"}}}}

2个问题

  1. 错误消息清楚地指出,不能映射抽象类
  2. 您正在使用Queryable扩展Project().To<T>(),在这种情况下,它似乎受到了linq提供者的限制,如本文所述

=>让你的基础级混凝土

=>从IEnumerable<T>而不是IQueryable<T>映射,而不使用Queryable扩展。

最新更新