Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the GET method on asp.net Web API return IQueryable?

In asp.net Web Api2, when you create an async web api controller for a model with entity framework, by default the first method in the new controller is like this:

 public IQueryable<MyModel> GetMyModel()
 {
     return db.MyModel;
 }

The JSON output from this method is just an array of all of the MyModel entries. Meanwhile, all of the other methods for POST,PUT,GET(int id), and DELETE are marked as async and return Task<IHttpActionResult>. Why isn't the first GET method in the same style, something like this:

 public async Task<IHttpActionResult> GetMyModel()
 {
     return Ok(await db.MyModel.ToArrayAsync());
 }

I've tried this, and it produces identical JSON output.

like image 709
Matthew Avatar asked Jan 21 '16 13:01

Matthew


1 Answers

Because Web API will materialize the result anyway, so the minimum code required is generated.

By calling ToArrayAsync() you're essentially doing unnecessary work, that will be done for you later anyway.

like image 120
CodeCaster Avatar answered Oct 16 '22 23:10

CodeCaster