开发者

Delaying LINQ to SQL Select Query Execution

I'm building an ASP.NET MVC site that uses LINQ to SQL.

In my search method that has some required and some optional parameters, I want to build a LINQ query while testing for the existence of those optional parameters.


Here's what I'm currently thinking:

using(var db = new DBDataContext())
        {
            IQueryable<Listing> query = null;

            //Handle required parameter
            query = db.Listings.Where(l => l.Lat >= form.bounds.extent1.latitude && l.Lat <= form.bounds.extent2.latitude);

            //Handle optional parameter
            if (numStars != null)
                quer开发者_如何学编程y = query.Where(l => l.Stars == (int)numStars);

            //Other parameters...

            //Execute query (does this happen here?)
            var result = query.ToList();

            //Process query...

Will this implementation "bundle" the where clauses and then execute the bundled query? If not, how should I implement this feature?

Also, is there anything else that I can improve?

Thanks in advance.


Yes, the query will only be executed once ToList() is called. If you follow this pattern and are using anonymous types, be aware of OrderBy() returning IOrderedQueryable instead of IQueryable.

Be aware that you are able to just iterate over the IQueryable, you don't have to call ToList to access the data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜