← Tutti gli articoli

Filtering data in the Entity Data Framework

27 August 2012  ·  EDF · Article  ·  385 visite

One of the most fundamental aspects of the Entity Framework querying is filtering data

  1. string  contentTitle =  "ASP.NET" ;  
  2. bool  orderByTitleAsc= true ;  
  3.   
  4. var query = from c in context.Contents select c;  
  5.   
  6. if  (contentTitle !=  null )  
  7.   query = from c in query where c.ContentTitle == contentTitle select c;  
  8.   
  9. if  (orderByTitle)  
  10.   query = from c in query orderby c.Title select c;;  
  11. else   
  12.   query = from c in query orderby c.Title descending select c;  
  13.   
  14. foreach (Contents c  in  query)  
  15.   Console.WriteLine(c.Title );  
 
LINQ allows any IQueryable to appear in the from part of another query, and this code takes advantage of this to augment the original query with additional operators.
Notice that the original query simply returns all contents.
If the contentTitle parameter is specified, the code adds a where clause to filter contents based on the specified value and replaces the original query.
You can also sort the query results based on the value of the orderByTitleAsc.
Si è verificato un errore imprevisto. Ricarica

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please retry or reload the page.