Search code examples
c#odataasp.net-web-api

OData's Delta and type parameter


I'm using the latest OData package.

I have this abstract class:

public abstract class EntityODataController<TEntity, TDto> : BaseODataController
{
    public EntityODataController(ILogService logService) : base(logService) { }

    [HttpGet]
    public abstract IHttpActionResult Get(int id);

    [AcceptVerbs("PATCH", "MERGE")]
    public abstract Task<IHttpActionResult> Update([FromODataUri] int id, Delta<TDto> delta, CancellationToken ct);
}

When I compile I get the following error:

The type 'TDto' must be a reference type in order to use it as parameter 'TEntityType' in the generic type or method 'System.Web.Http.OData.Delta'

I have references to both System.Web.Http.OData and System.Web.OData in the project (they got included when installing the package).

And in the class I first used one namespace and then the other. But I still get the error.

Is there a workaround?


Solution

  • It is not a problem with your refernces it is that TDto can be any type at all you need to add a generic type restriction to TDto to restrict it to reference types.

    public abstract class EntityODataController<TEntity, TDto> : ODataController where TDto : class
    {
        public EntityODataController(ILogService logService) : base(logService) { }
    
        [HttpGet]
        public abstract IHttpActionResult Get(int id);
    
        [AcceptVerbs("PATCH", "MERGE")]
        public abstract Task<IHttpActionResult> Update([FromODataUri] int id, Delta<TDto> delta, CancellationToken ct);
    }