I have Project entity and ProjectDTO. I\'m trying to create an WebAPI controller method that can take and return ProjectDTOs and make it support OData.
The problem i
I think the easiest way to do this is by using AutoMapper. So, for your DTO
[DataContract(Name = "Products")]
public class ProductDTO
{
[Key]
[DataMember]
public string MyProductMember1 { get; set; }
[DataMember]
public string MyProductMember2 { get; set; }
...
}
you should write somewhere in AutoMapper configuration:
Mapper.CreateMap();
and somewhere in building IEdmModel for OData:
builder.EntitySet("Products");
and the code for your controller will look like
public class ProductsController : ODataController
{
[EnableQuery]
public IHttpActionResult Get()
{
var products = context.Products; // IQueryable
return Ok(products.Project().To());
}
}
This way you don't need to expose your ORM entities directly, and can use OData for filtering, paging, count, and even expand nested collections, and for EF it will translate into corresponding SQL requests using table to which Product is mapped. But be careful: for more complicated cases (nested collections, for example) it may result in non-optimal SQL request.