Search code examples
asp.net-web-apiodataasp.net-web-api-odata

asp.net web api odataNo IdLink


I'm using Odata with web api and get this error:

 <m:innererror>
<m:message>
The 'ObjectContent`1' type failed to serialize the response body for content type       'application/json; charset=utf-8'.
</m:message>
<m:type>System.InvalidOperationException</m:type>
 <m:stacktrace/>
<m:internalexception>
 <m:message>
No IdLink factory was found. Try calling HasIdLink on the EntitySetConfiguration for    'Tag'.
</m:message>
 <m:type>System.InvalidOperationException</m:type>

Here is my OData configuration:

  config.Routes.MapODataRoute("ODataRoute", "odata", CreateModel());
   static IEdmModel CreateModel()
    {
        var modelBuilder = new ODataModelBuilder();

        modelBuilder.EntitySet<Tag>("Tag");
        modelBuilder.EntitySet<Post>("Post");

        return modelBuilder.GetEdmModel();
    }

Here is my OData controller

  public class TagController : EntitySetController<Tag, int>
{
    private readonly IUnitOfWork _unitOfWork;

    public TagController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }


    public override IQueryable<Tag> Get()
    {
        return _unitOfWork.BlogTagQueries.GetAllTags().AsQueryable();
    }

    protected override Tag GetEntityByKey(int key)
    {
        return _unitOfWork.BlogTagQueries.GetTagById(key);
    }
}

Can anyone please tell me, why am I getting this error ?


Solution

  • You probably were trying to use ODataConventionModelBuilder instead of ODataModelBuilder. The convention builder would automatically create the link generating factories for you.

    So, you can change the code like below:
    var modelBuilder = new ODataConventionModelBuilder();

    if you are curious as to how to create link factories yourself, you can check the following sample(specifically the file ODataServiceSample/ODataService/ModelBuilder.cs):

    http://aspnet.codeplex.com/sourcecontrol/latest#Samples/WebApi/ODataServiceSample/ReadMe.txt