c# – 不支持输入类型为“Domain.Entities.Request”的“TypeIs”表达式和“Domain.Entities.Base”类型的检查

我收到这个错误:

The ‘TypeIs’ expression with an input of type ‘Domain.Flood.Entities.Things.SomeObject’ and a check of type ‘Domain.Entities.Base’ is not supported. Only entity types and complex types are supported in LINQ to Entities queries.

我正在尝试调用我的OData API并在我的对象上展开CreatedBy属性. CreatedBy属性位于基类中,是一种User.所以我的基类看起来像这样:

[DataContract(Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
    public abstract class Base
    {    
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [DataMember]
        public int Id { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string Description { get; set; }    

        private User createdBy;    
        [DataMember]
        public virtual User CreatedBy
        {
            get
            {
                return createdBy;
            }
            set
            {
                createdBy = value;
            }
        } 
    }

当我尝试从基类继承我的小部件,并且我还想包含名为CreatedBy的User对象时,我收到此错误.如果我不扩展CreatedBy对象,我不会得到错误.这是奇怪的部分,我有另一个User属性不在基类上,而是在我的SomeObject类中称为AssignedTo.如果我扩展它,一切都很好.所以在基类上展开User对象,没有bueno.将用户对象向上扩展几个级别,bueno.

     {
         Container.SendingRequest += new EventHandler<SendingRequestEventArgs>(OnSendingRequest);
         ViewBag.Data = Container.SomeObject.Expand("Address, CreatedBy").ToList();
         return View();
     }

这是堆栈跟踪:

Exception Details: System.Data.Services.Client.DataServiceClientException: <?xml version="1.0" encoding="utf-8"?>
<m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
 <m:code />
 <m:message xml:lang="en-US">An error has occurred.</m:message>
 <m:innererror>
   <m:message>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/atom+xml; charset=utf-8'.</m:message>
   <m:type>System.InvalidOperationException</m:type>
   <m:stacktrace></m:stacktrace>
   <m:internalexception>
     <m:message>The 'TypeIs' expression with an input of type 'Domain.Flood.Entities.Things.SomeObject' and a check of type 'Domain.Entities.Base' is not supported. Only entity types and complex types are supported in LINQ to Entities queries.</m:message>
     <m:type>System.NotSupportedException</m:type>
     <m:stacktrace>   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.GetIsOrAsTargetType(ExpressionType operationType, Type toClrType, Type fromClrType)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.IsTranslator.TypedTranslate(ExpressionConverter parent, TypeBinaryExpression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.ConditionalTranslator.TypedTranslate(ExpressionConverter parent, ConditionalExpression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MemberInitTranslator.TypedTranslate(ExpressionConverter parent, MemberInitExpression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MemberInitTranslator.TypedTranslate(ExpressionConverter parent, MemberInitExpression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MemberInitTranslator.TypedTranslate(ExpressionConverter parent, MemberInitExpression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding&amp; binding)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression&amp; source, DbExpressionBinding&amp; sourceBinding, DbExpression&amp; lambda)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SelectTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert()&#xD;
  at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)&#xD;
  at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClassb.&lt;GetResults&gt;b__a()&#xD;
  at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)&#xD;
  at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClassb.&lt;GetResults&gt;b__9()&#xD;
  at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)&#xD;
  at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)&#xD;
  at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator&gt;b__0()&#xD;
  at System.Lazy`1.CreateValue()&#xD;
  at System.Lazy`1.LazyInitValue()&#xD;
  at System.Lazy`1.get_Value()&#xD;
  at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()&#xD;
  at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteFeed(IEnumerable enumerable, IEdmTypeReference feedType, ODataWriter writer, ODataSerializerContext writeContext)&#xD;
  at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteObjectInline(Object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)&#xD;
  at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteObject(Object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)&#xD;
  at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)&#xD;
  at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext)&#xD;
--- End of stack trace from previous location where exception was thrown ---&#xD;
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)&#xD;
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)&#xD;
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult()&#xD;
  at System.Web.Http.WebHost.HttpControllerHandler.&lt;WriteBufferedResponseContentAsync&gt;d__14.MoveNext()</m:stacktrace>
   </m:internalexception>
 </m:innererror>
</m:error>

阅读错误信息,我可以看到Linq to Entities正试图将一件事转换成另一件事,但到目前为止,我真的不知道.

我注意到的另一件事是我的OData元数据显示了所有内容,而不仅仅是具有数据合同的内容.它过去只包含具有数据合同的类.这有点奇怪吗?我浏览了我的源代码控制,看看在最后几个更改集中发生了什么变化,我没有看到与我的Base类,Users类或我的SomeObject类有什么关系.与我的API无关.

如果我能更清楚,请告诉我.我觉得我要留下一些东西.

最佳答案 如果您仔细阅读错误:

The ‘TypeIs’ expression with an input of type
‘Domain.Flood.Entities.Things.SomeObject‘ and a check of type
‘Domain.Entities.Base‘ is not supported.

这意味着OData尝试一个查询,使得EF生成一个具有“TypeIs”功能的查询本身很好,但TypeIs的两个操作数必须是实体类型或复杂类型:

Only entity types and complex types are supported in LINQ to Entities
queries.

也就是说,在EF DbContext中,使用模型构建器,您必须确保上下文将SomeObject和Base都知道为实体类型或复杂类型.这是用Fluent API做的:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Base>(); //EF should crawl and configure all derived types as well.
}

另外,使用DbModelBuilder.Ignore()时要特别注意不要忽略任何重要类型.

更新:

您还可以告诉OData将所有超类继承的属性视为ODataConventionModelBuilder的继承类型:

使用System.Web.OData:

modelBuilder.EntityType<SomeObject>().DerivesFromNothing();

使用System.Web.Http.OData:

modelBuilder.Entity<SomeObject>().DerivesFromNothing();
点赞