实体框架在我的WebAPI Mvc4解决方案中无法使用

时间:2012-09-28 20:50:20

标签: entity-framework asp.net-web-api

我使用流畅的api制作了实体框架代码。

我有一个web api控制器:

public class NewsController : ApiController
{
    private TrafficTheoryContext db = new TrafficTheoryContext();

    // GET api/News
    public IEnumerable<News> GetNews()
    {
        //return new List<News> {
       //  new News{ Title = "Featuring Azure ACS Authentication", Subtile="Hello "}};
        return db.News.AsEnumerable();
    }
} 

如果我发出获取请求,我会收到错误:

此XML文件似乎没有与之关联的任何样式信息。文档树如下所示。

<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.News_786DE29B12691F869E9C9DF523A808EABE06546C3FCE3354F77875B83B9EB51C' with data contract name 'News_786DE29B12691F869E9C9DF523A808EABE06546C3FCE3354F77875B83B9EB51C:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver 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 DataContractSerializer.
</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.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle) at WriteArrayOfNewsToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) 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.<>c__DisplayClass7.<WriteToStreamAsync>b__6() at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)
</StackTrace>
</InnerException>
</Error>

如果我只是返回一份新闻列表,那就会被罚款。我注意到这些文章附有某种我不知道的名字?

如何让webapi工作?

3 个答案:

答案 0 :(得分:4)

我相信您会因为为您的实体生成动态代理而获得此异常。如果查看异常消息,则实际上并不是序列化新闻类型,而是System.Data.Entity.DynamicProxies.News_786DE29B12691F869E9C9DF523A808EABE06546C3FCE3354F77875B83B9EB51C类型。此类型是由Entity Framework为您创建的,以支持延迟加载。您可以在此处找到有关动态代理的更多详细信息:http://msdn.microsoft.com/en-US/data/jj592886。 我不太了解WebAPI,但例外实际上说明了需要做什么:

输入带有数据合约名称的'System.Data.Entity.DynamicProxies.News_786DE29B12691F869E9C9DF523A808EABE06546C3FCE3354F77875B83B9EB51C' 'News_786DE29B12691F869E9C9DF523A808EABE06546C3FCE3354F77875B83B9EB51C:HTTP://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' 不是预期的。 考虑使用DataContractResolver或将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用KnownTypeAttribute 属性或将它们添加到传递给DataContractSerializer的已知类型列表中。

由于类型是自动创建的,因此无法放置属性。因此,我将重点关注“考虑使用DataContractResolver”和“将它们添加到传递给DataContractSerializer的已知类型列表”部分。

顺便问一下您使用的EF版本是什么?我想我之前看过这个问题,它已在EF5 RTM中修复。

答案 1 :(得分:4)

我在Mcv5项目中遇到同样的问题,当我禁用代理创建时,每件事情都像魅力一样。我希望它也能帮到你。

DbContext.Configuration.ProxyCreationEnabled = false;

答案 2 :(得分:0)

而不是.AsEnumerable,使用.ToList()。我也很好奇你是如何创建和破坏数据上下文的。