The 'ObjectContent`1' type failed to seria

2019-08-27 02:29发布

This question already has an answer here:

I have an MVC5 app, and I have included WebAPI inside it. I tested it and it worked fine for simple string and stuff. Then I tried to do something like this:

public Business Get(string id)
{
     return db.Businesses.Where(b => b.Id == id).FirstOrDefault();
}

And I got the above mentioned error. Please note that Business is a custom type that I created in my models folder. In my WebApiConfig file I have something like this:

var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
formatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Any idea how to solve the problem?

EDIT:

Some more of the error message:

Type 'System.Data.Entity.DynamicProxies.Business_32C47B90BA261D075748CEC009DA52F8C6D893134F8D33848A7F856F76F50D55' with data contract name 'Business_32C47B90BA261D075748CEC009DA52F8C6D893134F8D33848A7F856F76F50D55: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.System.Runtime.Serialization.SerializationException

1条回答
女痞
2楼-- · 2019-08-27 03:10

I found the solution. I simply needed to include this line of code:

DbContext.Configuration.ProxyCreationEnabled = false;
查看更多
登录 后发表回答