Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C api给出错误“ObjectContent'1'类型未能序列化内容类型'application/xml;charset=utf-8'的响应正文。”_C#_.net_Entity Framework_Api_Asp.net Web Api - Fatal编程技术网

C# C api给出错误“ObjectContent'1'类型未能序列化内容类型'application/xml;charset=utf-8'的响应正文。”

C# C api给出错误“ObjectContent'1'类型未能序列化内容类型'application/xml;charset=utf-8'的响应正文。”,c#,.net,entity-framework,api,asp.net-web-api,C#,.net,Entity Framework,Api,Asp.net Web Api,我完全遵循了这一点,但当我运行我的代码时,我得到了这个错误消息 <Error> <Message>An error has occurred.</Message> <ExceptionMessage> The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'. </Exc

我完全遵循了这一点,但当我运行我的代码时,我得到了这个错误消息

 <Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'System.Data.Entity.DynamicProxies.Player_B392F8ACFF7986B6E577FBE0EA4EC58EB44F1C4138CB96BE272A810004835B21' with data contract name 'Player_B392F8ACFF7986B6E577FBE0EA4EC58EB44F1C4138CB96BE272A810004835B21:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>
<StackTrace>
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__22.MoveNext()
</StackTrace>
</InnerException>
</Error>
我不明白我的代码在哪里失败,因为它与教程相同

例如,控制器如下所示:

使用制度; 使用System.Collections.Generic; 使用System.Linq; Net系统; 使用System.Net.Http; 使用System.Web.Http; 使用欧足联APIDataAccess; 名称空间UEFA_API.Controllers { [RoutePrefixapi/Match] 公共类匹配控制器:ApiController { [路线] 公共数字获取 { usingUEFAEntities实体=新的UEFAEntities { return entities.Match.ToList; } } [路由{id:int}] 公共匹配Getint id { 使用UEFAEntities实体=新UEFAEntities { 返回entities.Match.FirstOrDefaulte=>e.ID==ID; } } }
} 显然是数据库中的外键出了问题。我用相同的数据创建了一个新数据库,但没有外键,现在我的应用程序运行良好


我希望我也能在这个问题上帮助其他人。

早期的实体框架版本,即Core 2.1之前的版本,在知道可以延迟加载数据时,默认情况下为数据模型使用代理类。例如,如果您有一个具有类子对象集合的类父对象,则默认情况下,当您通过以下方式加载父对象时

var parent = entities.Parents.FirstOrDefault(p=>p.Id==pid)
默认情况下,EF将在您首次尝试引用它们之前不会加载相关的childred

e、 g.只在你写的地方

var child = parent.Children.Where(c=>c.SomeProperty==true)
将发送一个新的SQL查询来获取子项。这是通过在运行时为父对象生成一个对您透明的代理类来实现的,该类检测到您希望访问子集合并发出SQL、进行映射等

不幸的是,由于各种原因,这些代理类不适合序列化(如果有的话)。因此,您将收到错误消息。EF Core 2.1更改了一些内容,因此默认情况下禁用了延迟加载,您必须启用它。但是,如果您使用的是任何早期版本,包括非核心EFs,则默认情况下它处于启用状态

这也解释了为什么在没有外键的情况下创建一个新数据库是有效的,因为EF将无法推断与子对象的关系,因此它不会创建代理,这意味着您正在处理的类现在是我们所称的POCO普通旧CLR对象。但是,您正在剥夺自己和EF在关系数据库中拥有相关对象的能力,从长远来看,这可能不是一件好事:

就更好的解决方案而言,您可以选择以下几种方法:关闭代理创建,或在序列化之前提取整个对象图:

var parent = entities.Parents.Include("Children").FirstOrDefault(p=>SomeCondition);
这将一次性加载整个父实体及其所有子实体,并避免出现问题;但是,这并不总是理想的,因为您可能并不每次都需要子实体

但更好的是,不要直接公开EF模型,而是使用到DTO数据传输对象的映射

我推荐DTO;使用DTO的最大优点是,您不需要将EF实体暴露给外部世界,因为例如,可能有部分EF实体与消费者无关,或者您可能希望在返回之前对某些子集合进行聚合,等等


有一本很棒的指南可以更深入地讨论这些主题。

您的连接字符串是什么样子的?@RahulSharma???我指的是连接到数据库时的连接字符串。@RahulSharma抱歉的oeps。这是我的连接字符串'Data Source=MC-is-LEUK-\SQLEXPRESS;初始目录=欧足联;综合安全=真实;MultipleActiveResultSets=True;应用程序名称=EntityFramework'