WebAPI OData Error The ObjectContent type failed to serialize the response body for content type 'application/json...' WebAPI OData Error The ObjectContent type failed to serialize the response body for content type 'application/json...' asp.net asp.net

WebAPI OData Error The ObjectContent type failed to serialize the response body for content type 'application/json...'


Instead of the ODataModelBuilder, use ODataConventionModelBuilder like this,

var modelBuilder = new ODataConventionModelBuilder ();var products = modelBuilder.EntitySet<Product>("Products");IEdmModel model = modelBuilder.GetEdmModel();

ODataModelBuilder is a very low level class intended to be used when you want to configure the whole model explicitly. You need to tell it each and every property, each and every navigation property and then the self-links (id, edit and read) and the navigation links.

ODataConventionModelBuilder on the other hand, has some conventions to infer these things automatically. You need to configure something explicitly with the ODataConventionModelBuilder only if you deviate from the conventions.

If you still wish to use the ODataModelBuilder class, you should write code like this,

ODataModelBuilder modelBuilder = new ODataModelBuilder();var products = modelBuilder.EntitySet<Product>("Products");var product = products.EntityType;product.HasKey(p => p.ID);product.Property(p => p.Name);product.Property(p => p.Price);product.Property(p => p.Category);products.HasIdLink((ctxt) => ctxt.Url.ODataLink(new EntitySetPathSegment("Products"), new KeyValuePathSegment(ctxt.EntityInstance.ID)));IEdmModel model = modelBuilder.GetEdmModel();

Things get more complicated once you have navigation properties and related entitysets etc.