Search code examples
asp.net-web-apiodataasp.net-web-api-odataodata-v4

Created(entity) throw exception with composite key


I have an entity (MyEntity) that uses a composite key.

The entity is posted and inserted just fine, however when Created() is called it throws an InvalidOperationException with the message.

The edit link builder for the entity set 'MyEntity' returned null. An edit link is required for the location header.

public IHttpActionResult Post(MyEntity entity)
{
    entity = Repository.Insert(entity);
    Repository.Save();

    return Created(entity); // fails
}

Solution

    1. If you build the Edm model from convention model builder, it should work.

    private static IEdmModel GetEdmModel()
    {
          var builder = new ODataConventionModelBuilder();
          ...
          return builder.GetEdmModel();
    }
    

    1. if you build the Edm model from non-convention model builder, you should set the Id link builder then it can work:

    private static IEdmModel GetEdmModel2()
    {
        var builder = new ODataModelBuilder();
        ...
        builder.EntitySet<MyEntity>("MyEntitys").HasEditLink(p => new Uri("http://anylink/"), false);
    
        return builder.GetEdmModel();
    }