Chapter64:IQueryableinterface

No Comments

Section64.1:TranslatingaLINQquerytoaSQLquery

The IQueryableand IQueryable<T>interfaces allows developers to translate a LINQ query (a ‘language-integrated’ query) to a specific datasource, for example a relational database. Take this LINQ query written in C#:

varquery=frombookinbooks

wherebook.Author==”StephenKing”selectboo

k;

IfthevariablebooksisofatypethatimplementsIQueryable<Book>thenthequeryabovegetspassedtothe provider (set on the IQueryable.Providerproperty) in the form of an expression tree, a data structure that reflects the structure of the code.

Theprovidercaninspecttheexpressiontreeatruntimetodetermine:

  • that there is a predicate for the Authorproperty of the Bookclass;
  • that the comparison method used is ‘equals’ (==);
  • thatthevalueitshouldequalis”StephenKing”.

WiththisinformationtheprovidercantranslatetheC#querytoaSQLqueryatruntimeandpassthatquerytoa relationaldatabasetofetchonlythosebooksthatmatchthepredicate:

SELECT*

FROMBooks

WHEREAuthor=’StephenKing’

Theprovidergetscalledwhenthequeryvariableisiteratedover(IQueryableimplementsIEnumerable).

(Theproviderusedinthisexamplewouldrequiresomeextrametadatatoknowwhichtabletoqueryandtoknow howtomatchpropertiesoftheC#classtocolumnsofthetable,butsuchmetadataisoutsideofthescopeofthe IQueryableinterface.)

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Recent Posts