Introduction
The background for this quick article is based on how to properly pass along OData query parameters through to Entity Framework.
To setup your Entity Framework Database First project, I recommend familiarizing yourself with the content in the following links:
Once you have your Entity Framework project created, in an MVC project, you can create the following controller action method to access data using OData.
Next you need to install the following into your MVC project through Nuget:
Once these have been installed, I suggest reviewing OData Using C#, MVC, WebAPI,
Entity Framework, Dependency Injection (DI)/Inversion of Control (IoC) and Kendo UI.
Direct Entity Framework Access with OData
If you wish to pass along OData query options for Entity Framework to process (recommended), the following code will allow you to do this:
public IEnumerable<USER> Get(ODataQueryOptions<USER> options)
{
var dbContext = new ATMS.DAL.AtmsContext();
var ret = options.ApplyTo(dbContext.USERS).Cast<USER>().ToArray();
return ret;
}
Note that we are returning IEnumerable
and not IQueryable
.
Take note, that when using a DI/IoC container, code refactoring has to be done to your Entity Framework project. Details discussed in the link above.
Points of Interest
Just because you see a filtered data set on the client, doesn't mean that the entire transport process has been efficient. You need to ensure that you are returning the optimal
amount of data from your database, rather than large inflated data sets and filtering later. There are a few "gotcha's" that this article identifies.
For a more detailed way of accomplishing this and how to refactor your Entity Framework project for access through a generic repository, see: OData Using C#, MVC, WebAPI, Entity Framework, Dependency Injection (DI)/Inversion of Control (IoC) and Kendo UI.
I am a technical architect/senior software engineer, technical trainer, entrepreneur.
I have worked in several sectors from healthcare, to entertainment and global intelligent traffic systems, using .Net, SQL, NoSQL and some of the latest technologies to deliver quality software systems for clients.
Past tech flavors include C#, WCF, SOA, MVC, MVVM, Silverlight, Assembler, Pascal, VB, Java/J2EE/EJB/JDBC, Perl, NLTK, TSQL, NoSQL, KendoUI, NodeJS, SignalR, Backbone JS, Angular JS, Latest .Net technologies, Amazon AWS...