Reputation: 81
I am going through a tutorial for asp.net and C# and the author used some code that I am trying to understand. I have an idea of what it does, but I just wanted to make sure.
public IQueryable<Category> GetCategories()
{
var db = new WingtipToys.Models.ProductContext();
IQueryable<Category> query = db.Categories;
return query;
}
I am a little confused by
IQueryable<Category>
as well as the line
IQueryable<Category> query = db.Categories;
What I think it does is that it is a method called GetCategories() that only accepts Category objects. The method defines a new instance productcontext, it then runs some type of query and returns it. I could be close or way off. I just want to make sure.
Upvotes: 0
Views: 183
Reputation: 8656
So I think the part you're having trouble with is the generic return type in the method signature, it can be a strange syntax if you haven't come across it before.
Your method is returning a type of IQueryable<Category>
, so you're going to be returning an object that implements the interface IQueryable<T>
, specifically one which is implemented to work specifically with Category
objects.
If you wanted to create a list of strings, you'd do something like:
MyStrings = new List<string>();
And if you wanted to create a method to return a list of strings:
public List<string> FetchMyStrings(); // List<string> is your return type.
In your case, you're returning a list of Category
objects:
public List<Category> FetchMyCategories(); // List<Category> is your return type.
For some excellent explanations of IQueryable<T>
, and why you'd be interested in it, I'd recommend the answers here:
What is the difference between IQueryable<T> and IEnumerable<T>?
The rest of the code seems to initialise a new database connection, and returns a queryable object, allowing you to get at the categories for use elsewhere in your code.
Upvotes: 1
Reputation: 658
The IQueryable return type is used to indicate you want C# to pass along any filters that you use on the GetCategories() method to be passed directly to the database. Even though the method is setup to pass all categories back, you can limit them at a higher level. This saves you from having to create multiple methods for each filter you can think of that goes back to the database.
Here is link to a StackOverflow Example about the differences between IEnumerable and IQueryable
Upvotes: 1
Reputation: 30837
... method called GetCategories() that only accepts Category objects ...
IQueryable<Category>
is a type just like int
or string
so the method accepts nothing, it judt returns categories in a queryable way (IQueryable
).
Upvotes: 1