Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using EF and WebAPI, how can I return a ViewModel AND support IQueryable/OData? [duplicate]

I've got an ASP.NET WebAPI project. I've recently created EntityFramework entities for all my data tables. But I don't want to expose my data layer & schema to my users. How can I map my entities to a ViewModel (automapper?) and provide IQueryable return type so that my API supports OData?

OData supports query composition and SQL-like parameters. I guess I'd need to provide some kind of 2-way translation for the query-composition part? Does that mean a custom LINQ provider? I hope it's easier than that.

Or should I give up on IQueryable/OData?

like image 358
Eric Falsken Avatar asked Feb 21 '13 17:02

Eric Falsken


1 Answers

I found the answer here: Web API Queryable - how to apply AutoMapper?

Instead of using [Queryable] you can use a parameter of type ODataQueryOptions<T> to apply OData operations against any type or LINQ query you wish. Here's a great example that doesn't even need to use AutoMapper:

public virtual IQueryable<PersonDto> Get(ODataQueryOptions<Person> odataQuery){
    odataQuery.Validate(new ODataValidationSettings(){
        AllowedFunctions = AllowedFunctions.AllMathFunctions
    });
    var people = odataQuery.ApplyTo(uow.Person().GetAll());
    return ConvertToDtos(people);
}

Here's the Microsoft page explaining the specifics of this usage. (about half way down)

like image 156
Eric Falsken Avatar answered Sep 20 '22 05:09

Eric Falsken