Web API and EF cause InvalidOperationException

自闭症网瘾萝莉.ら 提交于 2020-01-03 18:04:19

问题


I have 3 projects in my solution: DataModel (EF), DAL which works with Entities from DataModel and MVC Web API.

There are only 2 very simple entities: Person, Address with 3 simple fields in each of them and Person has the Address field (so these 2 entities are linked)

In my DAL I have a method that returns me the list of all the Persons, the content is very simple: return context.Person.ToList();

Now In my Web API I'm simply calling for the GetPersons() method and trying to return it. And here I get a strange error message:

"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"$id":"2","Message":"An error has occurred.",...

When I debug I can see that I do have the data from my GetPersons method. I also googled and found the only solution: I should have added the following lines into my start config:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

But it does not help.

I also tried to populate the list manually without using the database: and in this case it works.

I have a strong impression that it has something to do with EF but I don't know exactly what's that.


回答1:


  • Step by Step guide...

Step 1: Go to your Entity Project and then find the name of the class which inherits from DbContext class.

For Example: If the class name is MyProjectEntities as follows:

public partial class MyProjectEntities : DbContext
{
   //Auto Generated statements if EF is used.
}

Step 2: Go to your WebApi Project find the controller which inherits from ApiController and then create the instance for the MyProjectEntities class within that controller.

For Example: If the Api Controller name is PersonController then create the instance for MyProjectEntities as follows:

public class PersonController : ApiController
{
   MyProjectEntities DB = new MyProjectEntities();
}

Step 3: Create constructor for the PersonController class and set false to the ProxyCreationEnabled Property as follows:

public PersonController()
{
   DB.Configuration.ProxyCreationEnabled = false;
}

The final code within the web api controller looks similar to this:

public class PersonController : ApiController
{
   MyProjectEntities DB = new MyProjectEntities();
   public PersonController()
   {
      DB.Configuration.ProxyCreationEnabled = false;
   }
...
...



回答2:


The error was caused by cross references between Person and Address entities when serializing data. You should also add this line

json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

More from here




回答3:


You may change Get method your api return a list of objects with ToList(), ToArray() etc.

For Example if your Get Method like this.

public IQueryable<Language> GetLanguages()
{
  return db.Languages;
}

You can change it to

public IEnumerable<Language> GetLanguages()
{
    return db.Languages.ToArray();
}

To return Array of objects and free from serialization error. But correct way to solve this problem is told here detailed.



来源:https://stackoverflow.com/questions/23326702/web-api-and-ef-cause-invalidoperationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!