ASP.NET Web API - Entity Framework - 500 Internal .Include server error (param => param.field)

I am currently working on a Web API project using the Database-First method using the Entity Framework (which, as I know, is not the most stable of the platforms yet), but I am encountering something very strange.

When the GET method in my APIController tries to return all records to the DbSet using the LINQ Include () method, which will be invoked in this way, it will return a 500 error:

// GET api/Casinos public IEnumerable<casino> Getcasinos() { var casinos = db.casinos.Include(c => c.city).Include(c => c.state); return casinos.AsEnumerable(); } 

However, this method works fine and returns my data from my database:

 // GET api/States public IEnumerable<state> Getstates() { return db.states.AsEnumerable(); } 

So, in other cases, I proved that if it returns objects without LINQ queries, it works fine, but when there is an Include method used for DbContext, it fails.

Of course, trying to find this error is impossible even with the Fiddler, Chrome / Firefox dev tools and adding to GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

If someone allowed this, it would be nice to know a good resolution so that I can start returning my data! Thanks!)

PS I am using SQL Server 2012

+4
source share
1 answer

This is due to a serialization error (Json / XML). The problem is that you are directly trying to transfer your models by cable. For an example, see This:

 public class Casino { public int ID { get; set; } public string Name { get; set; } public virtual City City { get; set; } } public class State { public int ID { get; set; } public string Name { get; set; } [XmlIgnore] [IgnoreDataMember] public virtual ICollection<City> Cities { get; set; } } public class City { public int ID { get; set; } public string Name { get; set; } public virtual State State { get; set; } [XmlIgnore] [IgnoreDataMember] public virtual ICollection<Casino> Casinos { get; set; } } public class Context : DbContext { public Context() : base("Casino") { } public DbSet<Casino> Casinos { get; set; } public DbSet<State> States { get; set; } public DbSet<City> Cities { get; set; } } 

Pay attention to XmlIgnore and IgnoreDataMember . You need to limit yourself to avoiding serialization, so this doesn't happen in a circular fashion. In addition, the above model still does not work, because it has a virtual one. Delete virtual everywhere, namely City , Cities , Casinos and State , and then it will work, but it will be inefficient.

To summarize: Use DTO and send only the data that you really want to send, instead of sending your models directly.

Hope this helps!

+4
source

All Articles