Rich
Rich

Reputation: 6561

GET operation in ASP.NET API with Entity Framework

I've built an ASP.NET Web API using Entity Framework CodeFirst approach. The database tables it created represents a relational database as I expected. In the GET operation of my API I want to return values from 3 tables. Many of the examples I've seen only show a simple return like this:

// GET: api/Books
public IQueryable<Book> GetBooks()
{
    return db.Books;
}

where only the fields from the Books object are returned. This wouldn't be very useful because I have foreign keys to Author and BookType. Using Entity Framework and Web API how is it normally done to return values of fields from more than one table? I imagine I could use a linq query to join the tables and return the results. Is that the most efficient way to do this or is there a better way?

Thanks

Upvotes: 0

Views: 41

Answers (1)

Steve Land
Steve Land

Reputation: 4862

Your best bet would be to create a ViewModel, which incorporates all the data that you need to return to your UI, and then populate that from your database entities (normally using a tool like AutoMapper).

You then return the ViewModel rather than your database entities, which means that you can optimise and simplify the data being sent across the wire, as well as prevent possibly sensitive information from being exposed.

Here's an example of how this might be accomplished: http://bengtbe.com/blog/2009/04/14/using-automapper-to-map-view-models-in-asp-net-mvc/

Aside from the model aspect, I'd also suggest that you also try to avoid directly accessing your DB context in your controller actions, and rather abstract the data access into Repositories (and Services, if things start to get complex).

Upvotes: 1

Related Questions