I am using entity framwork in my Wep Api project. My model is realational and line this:
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
public class Article
{
public int Id { get; set; }
public int BlogId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public virtual Blog Blog { get; set; }
}
context is like this:
public class BloggingContext: DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Article> Articles { get; set; }
}
And I am using this in my asp.net Web Api controller.
public class BlogController: ApiController{
public IEnumerable<Blog> Get(){
var context = new BloggingContext();
return context.Blogs.ToList();
}
}
My approach is to get data with Lazy Loading, and serialize to JSON data as Web Api response.
context.Blogs.ToList()
returns the relational data (I see on breakpoint).
But Web Api result has error.
Exception Message:
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8
inner exception:
Error getting value from 'Blog' on 'System.Data.Entity.DynamicProxies.Article_D002A1ECE031410435306DCEF780AFF03EBB8BD36DA603662C993107FAEB1917 "ExceptionType": "Newtonsoft.Json.JsonSerializationException
I set my WebApiConfig.cs
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);