8

I have made Entity Framework Code First with fluent api.

I have a web api controller:

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();
    }
} 

If i make a get request i get an error:

This XML file does not appear to have any style information associated with it. The document tree is shown below.

<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>

If i just return a List of News it work fines. I noticed the clases are appended with some kind of name that i do not know what is?

What do i do to get the webapi to work?

3 Answers 3

4

I believe that you get this exception because of dynamic proxies generated for your entities. If you look at the exception message you don't actually serialize News type but the System.Data.Entity.DynamicProxies.News_786DE29B12691F869E9C9DF523A808EABE06546C3FCE3354F77875B83B9EB51C type. This type was created for you by Entity Framework to support lazy loading. You can find more details about dynamic proxies here: http://msdn.microsoft.com/en-US/data/jj592886. I don't know WebAPI very well but the exception actually says what's need to be done:

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.

Since the type is created automatically you cannot put the attribute. Therefore I would focus on the "Consider using a DataContractResolver" and "adding them to the list of known types passed to DataContractSerializer" parts.

Btw what version of EF are you using? I think I saw this issue before and it was fixed in EF5 RTM.

5
  • I uses : \EntityFramework.5.0.0\lib\net40\EntityFramework.dll and yes disabling lazy and proxi solved the issue, but im not sure if thats a good idea? Sep 28, 2012 at 22:16
  • I do not know what a DataContractResolver is, will google it. Sep 28, 2012 at 22:18
  • Re disabling lazy loading (or proxy creation) - it depends whether your application is using it or not. If it is then your app will crash if you expect a navigation property to be loaded automatically and it will not (because proxy creation was disabled)
    – Pawel
    Sep 28, 2012 at 22:27
  • Okay, i might want to enable proxies again. But i did not find a solution for getting it working. Might need someone with with more experience with webapi or WCF services. (assuming its the same problem). Oct 17, 2012 at 9:48
  • I had a similar problem using the Web API and EF and this solution solved my problem. This might be a good "definitive answer" candidate.
    – rmiesen
    Jun 9, 2014 at 17:11
4

I was also facing same problem in my Mcv5 Project when i disable the proxy creation every thing is working like charm.I Hope it will also help you.

DbContext.Configuration.ProxyCreationEnabled = false;
0

Instead of .AsEnumerable, use .ToList(). I'm also curious as to how you are creating and destroying your data context.

4
  • I did just put private TrafficTheoryContext db = new TrafficTheoryContext(); in the controller class. .AsEnumerable works fine - i found out that disabling lazyloading and proxy it works. Is this a bad idea? Sep 28, 2012 at 22:14
  • 1
    @s093294 - Well, by disabling it you are crippling part of EF's functionality. It means you need to explicitly .Include() all tables you want to use. Some people like that, others don't. Also, no proxy generation means no change tracking, and change tracking is very important in keeping the context's state synchronized. If you disable proxy creation, then you have to be very careful about how you insert, update, or delete records. Sep 28, 2012 at 22:50
  • Okay, using toList() didnt work either, its just a list of proxies. Sep 29, 2012 at 17:00
  • I never found a solution. List or IEnumerable do not matter. Oct 17, 2012 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.