<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>iqueryable &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/iqueryable/</link>
	<description>Feed of posts on WordPress.com tagged "iqueryable"</description>
	<pubDate>Sun, 06 Dec 2009 03:42:24 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Extend IQueryable instead of a certain dataprovider - more decoupled code]]></title>
<link>http://daniel.wertheim.se/2009/11/21/extend-iqueryable-instead-of-a-certain-dataprovider-more-decoupled-code/</link>
<pubDate>Sat, 21 Nov 2009 22:29:12 +0000</pubDate>
<dc:creator>Daniel Wertheim</dc:creator>
<guid>http://daniel.wertheim.se/2009/11/21/extend-iqueryable-instead-of-a-certain-dataprovider-more-decoupled-code/</guid>
<description><![CDATA[This is going to be a real short post and is more of an update to my last post (Entity validaton usi]]></description>
<content:encoded><![CDATA[This is going to be a real short post and is more of an update to my last post (Entity validaton usi]]></content:encoded>
</item>
<item>
<title><![CDATA[Apply paging to collections]]></title>
<link>http://danielsaidi.wordpress.com/2009/08/27/apply-paging-to-collections/</link>
<pubDate>Thu, 27 Aug 2009 08:01:03 +0000</pubDate>
<dc:creator>danielsaidi</dc:creator>
<guid>http://danielsaidi.wordpress.com/2009/08/27/apply-paging-to-collections/</guid>
<description><![CDATA[In order to apply paging to collections, I find it useful to use the following extension methods: //]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In order to apply paging to collections, I find it useful to use the following extension methods:</p>
<pre>   <span style="color:#008000;">/// &#60;summary&#62;
   /// Apply paging to an IEnumerable.
   /// &#60;typeparam name="TSource"&#62;The type that the collection contains.&#60;/typeparam&#62;
   /// &#60;param name="source"&#62;The data source.&#60;/param&#62;
   /// &#60;param name="page"&#62;The page index, starting at 0.&#60;/param&#62;
   /// &#60;param name="pageSize"&#62;The max number of items to return.&#60;/param&#62;
   /// &#60;returns&#62;The resulting object collection.&#60;/returns&#62;</span>
   public static IEnumerable&#60;TSource&#62; Page&#60;TSource&#62;(this IEnumerable&#60;TSource&#62; source, int? page, int pageSize)
   {
      return source.Skip((page ?? 0) * pageSize).Take(pageSize);
   }

   <span style="color:#008000;">/// &#60;summary&#62;
   /// Apply paging to an IQueryable.
   /// &#60;/summary&#62;
   /// &#60;typeparam name="TSource"&#62;The type that the collection contains.&#60;/typeparam&#62;
   /// &#60;param name="source"&#62;The data source.&#60;/param&#62;
   /// &#60;param name="page"&#62;The page index, starting at 0.&#60;/param&#62;
   /// &#60;param name="pageSize"&#62;The max number of items to return.&#60;/param&#62;
   /// &#60;returns&#62;The resulting object collection.&#60;/returns&#62;</span>
   public static IQueryable&#60;TSource&#62; Page&#60;TSource&#62;(this IQueryable&#60;TSource&#62; source, int? page, int pageSize)
   {
      return source.Skip((page ?? 0) * pageSize).Take(pageSize);
   }</pre>
<p>By adding them to an extension class within a certain namespace, all IQueryable and IEnumerable objects automatically receives paging functionality. You will then be able to write (for instance):</p>
<pre>      List&#60;string&#62; strings = new List&#60;string&#62; { "a","b", "c","d","e","f","g","h","i","j"};
      strings.Page(2, 2);</pre>
<p>And get a list that contains &#8220;c&#8221; and &#8220;d&#8221;.</p>
<p>Man, I really must start using a code tool, so that  I do not have to hack the code manually when writing these blogs  <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[IQueryable vs IEnumerable]]></title>
<link>http://ramanisandeep.wordpress.com/2009/08/26/iqueryable-vs-ienumerable/</link>
<pubDate>Wed, 26 Aug 2009 12:50:23 +0000</pubDate>
<dc:creator>ramanisandeep</dc:creator>
<guid>http://ramanisandeep.wordpress.com/2009/08/26/iqueryable-vs-ienumerable/</guid>
<description><![CDATA[The primary difference is that the extension methods defined for IQueryable&lt;T&gt; take Expression]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p align="justify">The primary difference is that the extension methods defined for <strong>IQueryable&#60;T&#62;</strong> take Expression objects instead of Functional objects, meaning the delegate it receives is an expression tree instead of a method to invoke. </p>
<p align="justify"><strong>IEnumerable&#60;T&#62;</strong> is great for working with in-memory collections, but <strong>IQueryable&#60;T&#62;</strong> allows for a remote data source, like a database or web service.</p>
<p align="justify"><strong>IEnumerable</strong> doesn’t have the concept of moving between items, it is a forward only collection. It’s very minimalistic; something that most any data source can provide. Using only this minimal functionality, LINQ can provide all of these great operators. </p>
<p align="justify"><strong>IQueryable&#60;T&#62;</strong> is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries). </p>
<p align="justify">Hope this helps !!!</p>
<p align="justify"><strong>Reference Links :</strong></p>
<ul>
<li>
<div align="justify"><a href="http://odetocode.com/Articles/738.aspx" target="_blank"><font color="#000000" size="1">C# 3.0 and Linq posted by scott</font></a></div>
</li>
<li>
<div align="justify"><a href="http://jonkruger.com/blog/2007/10/19/iqueryable-vs-ienumerable-in-linq-to-sql-queries/" target="_blank"><font color="#000000" size="1">IQueryable&#60;T&#62; vs. IEnumerable&#60;T&#62; in LINQ to SQL queries by Jon Kruger</font></a></div>
</li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Inserting an Item in IQueryable Object using Union Method and LINQ.]]></title>
<link>http://magicode.wordpress.com/2009/08/20/inserting-an-item-in-iqueryable-object-using-union-method-and-linq/</link>
<pubDate>Thu, 20 Aug 2009 16:18:32 +0000</pubDate>
<dc:creator>kaushal</dc:creator>
<guid>http://magicode.wordpress.com/2009/08/20/inserting-an-item-in-iqueryable-object-using-union-method-and-linq/</guid>
<description><![CDATA[Hi, Today I would like to show an interesting and useful example of how to insert an Item in IQuerya]]></description>
<content:encoded><![CDATA[Hi, Today I would like to show an interesting and useful example of how to insert an Item in IQuerya]]></content:encoded>
</item>
<item>
<title><![CDATA[LINQ to SQL quick tip]]></title>
<link>http://mrdotnet.wordpress.com/2008/11/07/linq-to-sql-quick-tip/</link>
<pubDate>Fri, 07 Nov 2008 08:04:34 +0000</pubDate>
<dc:creator>James</dc:creator>
<guid>http://mrdotnet.wordpress.com/2008/11/07/linq-to-sql-quick-tip/</guid>
<description><![CDATA[Quick tip:  If you are going to composite method calls together in order to make use of multiple met]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Quick tip:  If you are going to composite method calls together in order to make use of multiple method calls to refine the SQL Query to be generated, make sure the calls are made against IQueryable&#60;T&#62; objects and not IEnumerable&#60;T&#62;.</p>
<p>LINQ method calls (Where, Skip, Take, Count, etc) against IQueryable&#60;T&#62; have different extension methods that get called compared to those that get called when called against an IEnumerable&#60;T&#62; argument.</p>
<p>To illustrate this, consider the following design.  I have a model which only does a few things, but to reduce the amount of code duplication I split the query refinements into individual methods.  I have a base method which just selects the data from the table.  Another method which will perform a Where query on data passed in, another which will Page the data passed in, and another which will just count the number of rows in the data passed in.</p>
<p>In other words, I can do this:</p>
<pre>IEnumerable&#60;TEntity&#62; GetSearchResults( string search, int page )
{
  IEnumerable&#60;TEntity&#62; results = QueryData();
  results = SearchData( results, search );
  results = PageData( results, page, Constants.ResultsPerPage );

  return results;
}</pre>
<p>If these methods take and return IEnumerable&#60;T&#62; bad things start to happen, foremost is that the base query selects everything out of the table.  The Where query is all performed client side rather than being generated into the SQL query, and the same for the paging and counting!</p>
<p>Swap out IEnumerable&#60;T&#62; for IQueryable&#60;T&#62; and things begin to work well though.  The Where query is generating Where clauses in SQL and the same goes for the other methods.  And since IQueryable&#60;T&#62; requires implementers to also implement IEnumerable&#60;T&#62;, at any point in time I can decide to stop chaining calls and revert to IEnumerable&#60;T&#62; so method callers have no idea what the internal implementation of getting that IEnumerable&#60;T&#62; really is.</p>
<p>The only changes I need to make to the code I have above is to change the results variable to IQueryable&#60;T&#62;, as wells as the return type and the parameter type of QueryData, SearchData, and PageData to deal with IQueryable&#60;T&#62;.  The return type of the GetSearchResults method <em>doesn&#8217;t</em> need to be changed!</p>
<p>Edit: I tried to use the <a href="http://faq.wordpress.com/2007/09/03/how-do-i-post-source-code/">syntax highlighting feature of WordPress</a> provided by a google code project, but it failed miserably on the generics.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[LINQ and 3rd Party ORM Providers]]></title>
<link>http://blog.de-hao.com/2008/11/07/linq-and-3rd-party-orm-providers/</link>
<pubDate>Thu, 06 Nov 2008 18:21:55 +0000</pubDate>
<dc:creator>de-Hao</dc:creator>
<guid>http://blog.de-hao.com/2008/11/07/linq-and-3rd-party-orm-providers/</guid>
<description><![CDATA[Quite recently, Tim Mallalieu (Program Manager of the LINQ to SQL and Entity Framework Team) made it]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Quite recently, <a href="http://blogs.msdn.com/timmall/" target="_blank">Tim Mallalieu</a> (Program Manager of the LINQ to SQL and Entity Framework Team) made it clear in his blog post that the <a href="http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx" target="_blank">Entity Framework (LINQ to Entities) will get more focus in the .NET 4.0 build</a> as opposed to &#8220;LINQ to SQL&#8221; &#8212; which I am slowly growing to love by the day (in any case, you don&#8217;t want to know what I do by night). Yet, with my disappointment of the possible abandonment of the rather <strong>lightweight</strong> &#8220;LINQ to SQL&#8221; elucidation, comes my appreciation for third-party Object/Relational Mapping (ORM) implementations of LINQ.</p>
<p>I was first introduced to SubSonic earlier this year when I worked on the BoomerTowne project. I must admit, I quickly consumed the &#8220;Koolaid&#8221; with complete admiration. In fact, I feared that SubSonic will die a natural death with the introduction of LINQ to SQL, but my steadfast hope is now renewed.</p>
<p>In a recent discussion with <a href="http://www.hanselman.com/blog/AboutMe.aspx" target="_blank">Scott Hanselman</a> (on <a href="http://www.hanselminutes.com/" target="_blank">HanselMinutes</a>), <a href="http://blog.wekeroad.com/" target="_blank">Rob Conery</a> of <a href="http://www.codeplex.com/subsonic" target="_blank">Subsonic</a> (a popular .NET ORM/code generation tool) mentioned that Subsonic is working on implementing &#8220;<em>iQueryable</em>&#8221; in the next version of Subsonic. In other words, the next version of SubSonic will be bundled with a LINQ Provider (aka LINQ to SubSonic). NHibernate (another popular ORM tool) already has a LINQ provider (<a href="http://www.hookedonlinq.com/LINQToNHibernate.ashx" target="_blank">LINQ to NHibernate</a>) which affords developers the flexibility of writing queries using LINQ syntax. I think there are huge opportunities for open-source OR/M tools to step in and create even more lightweight and efficient LINQ providers. If you are already a die-hard SubSonic or NHibernate fan, it makes sense to &#8220;stick with the known&#8221; while dipping into LINQ.</p>
<p>If you are interested in creating your own LINQ Provider, head over to <a href="http://blogs.msdn.com/user/Profile.aspx?UserID=35601">Kevin Halverson</a>&#8217;s post on <strong><a href="http://blogs.msdn.com/kevin_halverson/archive/2007/07/10/how-to-implement-iqueryable.aspx">How to implement IQueryable (Part 1)</a>.</strong></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to use LINQ to SQL to batch queries and return Multiple Results without Stored Procedures, by Tony Wright]]></title>
<link>http://tonesdotnetblog.wordpress.com/2008/07/23/linq-to-sql-batches-and-multiple-results-without-stored-procedures-by-tony-wright/</link>
<pubDate>Wed, 23 Jul 2008 13:35:02 +0000</pubDate>
<dc:creator>tonywr</dc:creator>
<guid>http://tonesdotnetblog.wordpress.com/2008/07/23/linq-to-sql-batches-and-multiple-results-without-stored-procedures-by-tony-wright/</guid>
<description><![CDATA[I must admit I&#8217;ve been a bit disappointed with LINQ to SQL. I went looking for the concept of ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I must admit I&#8217;ve been a bit disappointed with LINQ to SQL. I went looking for the concept of LINQ batches, that is, the ability to execute more than one query in the same database request. I would have thought that this feature would be highly desirable. Instead of making an SQL request, waiting for all the results, making a second request, waiting for it&#8217;s results, then a third request, waiting for it&#8217;s results&#8230;well, you get my point.</p>
<p>If only you could make a single request and get all the results back in one hit. This is one of the benefits of sql server stored procedures. You can put a number of select statements in the stored procedure, call it from your client, and get all the results back via a DataReader or DataSet. With a DataReader, you get the first result back and then when you&#8217;ve finished reading all the rows of that result, you call the NextResult() method and it moves on to the next result and so on. With a DataSet, you can set up a DataAdapter, set it&#8217;s select statement to call a stored proc, and then call the Fill method to populate one-to-many DataTables within the DataSet. It&#8217;s very efficient, and can return the entire batch very quickly.</p>
<p>I often find implementations of the domain model, where someone has implemented a whole lot of objects in .net that hide the details of the underlying sql calls. Basically, as the developer traverses the object model, extra calls are created to the database. This causes all sorts of unnecessary traffic. In some instances, I&#8217;ve seen up to a hundred calls in a Page_Load!</p>
<p> With web sites, the ultimate goal is to try to only have a maximum of a single request per action. So (caching aside) a Page_Load would only call the database once to retrieve everything it needed to populate the page. After the page is populated, you modify some data and then click an Update button, and that action should perform another single request to the database to update the data and get any further results needed to ensure the state of the page is correct. I often achieve pretty close to this, so all that extra traffic is unnecessary and unwanted.</p>
<p>With LINQ to SQL, you shouldn&#8217;t need to call stored procedures just to batch queries &#8211; especially for simple ones. I mean, doesn&#8217;t that defeat the purpose of getting people to develop in LINQ, if as soon as it gets too hard, they say, nup, go off and use a stored procedure? Well, I&#8217;ve come up with a simple solution that does allow you to batch LINQ queries.</p>
<p>Here is an example of the types of queries you can execute using the batching function. Note that this performs a single query to the database, consisting of multiple select statements, and returns three enumerable collections.</p>
<p>  var StocktraderLevelQuery =<br />
   from StocktraderLevel in db.StocktraderLevels<br />
   where StocktraderLevel.ItemID==10<br />
   select Stocktrader;</p>
<p>  var StocktraderFunctionQuery =<br />
   from StocktraderFunction in db.StocktraderFunctions<br />
   select StocktraderFunction ;</p>
<p>  var StocktraderLevelAccessQuery =<br />
   from StocktraderLevelAccess in db.StocktraderLevelAccesses<br />
   select StocktraderLevelAccess;</p>
<p>  var mr = db.GetMultipleResults(StocktraderLevelQuery, StocktraderFunctionQuery, StocktraderLevelAccessQuery);</p>
<p>  StocktraderLevels = mr.GetResult&#60;StocktraderLevel&#62;();<br />
  StocktraderFunctions = mr.GetResult&#60;StocktraderFunction&#62;();<br />
  StocktraderLevelAccesses = mr.GetResult&#60;StocktraderLevelAccess&#62;();</p>
<p> <br />
To be able to do this, open up your project and add a dbml file. You do this by right-clicking on the project, selecting Add New Item, and then selecting LINQ to SQL classes. Type in your database name (in my case I called it Stocktrader.dbml). Then you use the Server Explorer to add a database connection to that database and drag the tables onto the dbml designer.</p>
<p>Behind the scenes, there is designer generated code, created by the LINQ to SQL custom tool. If you can&#8217;t see this file, you need to select &#8220;Show all files&#8221; from the toolbar. If you open that file, you can see that it&#8217;s a partial class. Good, that means we can extend it. So add a new class to the project. I named mine StocktraderExt.cs. Then I added the following code:</p>
<p>using System.Data;<br />
using System.Linq;<br />
using System.Data.Linq;<br />
using System.Data.SqlClient;<br />
using System.Collections.Generic;<br />
using System.Data.Common;</p>
<p>namespace Stocktrader.DBML<br />
{<br />
 public partial class StocktraderDataContext<br />
 {<br />
  private DbParameter CloneParameter(DbParameter src)<br />
  {<br />
   SqlParameter source = (SqlParameter)src;<br />
   SqlParameter destination = new SqlParameter();</p>
<p>   destination.Value = source.Value;<br />
   destination.Direction = source.Direction;<br />
   destination.Size = source.Size;<br />
   destination.Offset = source.Offset;<br />
   destination.SourceColumn = source.SourceColumn;<br />
   destination.SourceVersion = source.SourceVersion;<br />
   destination.SourceColumnNullMapping = source.SourceColumnNullMapping;<br />
   destination.IsNullable = source.IsNullable;</p>
<p>   destination.CompareInfo = source.CompareInfo;<br />
   destination.XmlSchemaCollectionDatabase = source.XmlSchemaCollectionDatabase;<br />
   destination.XmlSchemaCollectionOwningSchema = source.XmlSchemaCollectionOwningSchema;<br />
   destination.XmlSchemaCollectionName = source.XmlSchemaCollectionName;<br />
   destination.UdtTypeName = source.UdtTypeName;<br />
   destination.TypeName = source.TypeName;<br />
   destination.ParameterName = source.ParameterName;<br />
   destination.Precision = source.Precision;<br />
   destination.Scale = source.Scale;</p>
<p>   return destination;<br />
  }</p>
<p>  private SqlCommand CombineCommands(List&#60;DbCommand&#62; commandList)<br />
  {<br />
   SqlCommand batchCommand = new SqlCommand();<br />
   SqlParameterCollection newParamList = batchCommand.Parameters;<br />
   int commandCount = 0;<br />
   foreach (DbCommand cmd in commandList)<br />
   {<br />
    string commandText = cmd.CommandText;<br />
    DbParameterCollection paramList = cmd.Parameters;<br />
    int paramCount = paramList.Count;<br />
    for (int currentParam = paramCount &#8211; 1; currentParam &#62;= 0; currentParam&#8211;)<br />
    {<br />
     DbParameter param = paramList[currentParam];<br />
     DbParameter newParam = CloneParameter(param);<br />
     string newParamName = param.ParameterName.Replace(&#8220;@&#8221;, string.Format(&#8220;@{0}_&#8221;, commandCount));<br />
     commandText = commandText.Replace(param.ParameterName, newParamName);<br />
     newParam.ParameterName = newParamName;<br />
     newParamList.Add(newParam);<br />
    }<br />
    if (batchCommand.CommandText.Length &#62; 0)<br />
    {<br />
     batchCommand.CommandText += &#8220;;&#8221;;<br />
    }<br />
    batchCommand.CommandText += commandText;<br />
    commandCount++;<br />
   }<br />
   return batchCommand;<br />
  }</p>
<p>  public IMultipleResults GetMultipleResults(params IQueryable[] queryableList)<br />
  {<br />
   List&#60;DbCommand&#62; commandList = new List&#60;DbCommand&#62;();<br />
   foreach (IQueryable query in queryableList)<br />
   {<br />
    DbCommand cmd = this.GetCommand(query);<br />
    commandList.Add(cmd);<br />
   }<br />
   SqlCommand batchCommand = CombineCommands(commandList);<br />
   batchCommand.Connection = (SqlConnection)this.Connection;</p>
<p>   DbConnection cn = this.Connection;<br />
   cn.Open();</p>
<p>   DbDataReader dr = batchCommand.ExecuteReader(CommandBehavior.CloseConnection);<br />
   var mr = this.Translate(dr);<br />
   return mr;<br />
  }</p>
<p> }<br />
}</p>
<p>What I am doing here is passing a list of IQueryables into the GetMultipleResults method. The LINQ DbContext object exposes a GetCommand method. This enabled me to obtain the DbCommand object that would otherwise be used to execute the LINQ query. So I build up a list of DbCommand objects for all the queries in my parameter list.</p>
<p>Next, I decided to combine all the command objects into a single command (called the batch command). There are three parts to this. Firstly, the CommandText for each command can have parameters specified. In LINQ, they are always the same, starting at @p0 and working their way up, @p1, @p2, @p3 etc.</p>
<p>This isn&#8217;t a bad thing, because I can put in a counter that increments for every command that I am adding to the batch command, then substitute the name for a new name that includes my command counter. So @p0 becomes @0_p0 (the @p0 param for the first command). I am also using string.Replace to replace the parameters inside the CommandText, and I am building up a collection of new parameters for my new batch command. Note that this idea is based on the SqlCommandSet class that is hidden inside the SqlDataAdapter class. You could probably use this code as a basis for writing a standard batch command process for executing queries in bulk, if you wanted to.</p>
<p>After combining the DbCommand objects into one enormous command (potentially), I then attach to the DbContext connection, and execute the DbReader with an instruction to close the connection as soon as all data is read. No problem doing that because it&#8217;s a batch query &#8211; you shouldn&#8217;t need the connection afterwards as you&#8217;ve done all your queries in the one hit.</p>
<p>Finally, we need an object that has an interface of IMultipleResults. That&#8217;s done by another internal method, called Translate. Translate takes a DbDataReader as input, and returns multiple results from the reader.</p>
<p>Note these lines of code in the code section at the top:</p>
<p>  StocktraderLevels = mr.GetResult&#60;StocktraderLevel&#62;();<br />
  StocktraderFunctions = mr.GetResult&#60;StocktraderFunction&#62;();<br />
  StocktraderLevelAccesses = mr.GetResult&#60;StocktraderLevelAccess&#62;();</p>
<p>Basically, these retrieve the results in the order of the LINQ queries you passed to the GetMultipleResults method. And that&#8217;s it, you can now perform batch queries with LINQ to SQL.</p>
<p>I have provided the code here. Unfortunately wordpress only supports a few different file types, so here it is as a doc file: <a href="http://tonesdotnetblog.files.wordpress.com/2008/07/linqtosqlbatchqueries.doc">linqtosqlbatchqueries</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Refining queries in Linq.]]></title>
<link>http://peteohanlon.wordpress.com/2008/01/10/refining-queries-in-linq/</link>
<pubDate>Thu, 10 Jan 2008 09:59:12 +0000</pubDate>
<dc:creator>peteohanlon</dc:creator>
<guid>http://peteohanlon.wordpress.com/2008/01/10/refining-queries-in-linq/</guid>
<description><![CDATA[The more I play around with Linq, the more it really appeals to me. It really is amazing how powerfu]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>The more I play around with Linq, the more it really appeals to me. It really is amazing how powerful it is, and how flexible it can actually make your applications. &#8220;Examples&#8221; I hear you cry, &#8220;give me examples&#8221;. Who am I to deny you when you ask so nicely?</p>
<p>Quite often, when an record is deleted in a database, the application design mandates that the record isn&#8217;t physically deleted. Instead, it is given a status of Deleted. This means that retrieval of live records needs to take this status into account. Now, in stored procedures you would add a check for the status in each query that you perform against one of these tables. As you can imagine, this quickly becomes very tedious.</p>
<p>So, how can Linq help to make this situation better? Well one of the tricks that you can employ with Linq is refining queries, so you start with a general query and then refine it until you get to a specific query. So, how does this work in practice? Well, take a look at the following query to get all of the records from a table (cunningly called MyTable in this example):</p>
<pre>protected virtual IQueryable&#60;MyTable&#62; GetAll()
{
  IQueryable&#60;MyTable&#62; query = from myTable in context.MyTable // The context is the DataContext.
     select myTable;
  return query;
}</pre>
<p>Now, as you can see, this query retrieves all of the records from MyTable regardless of status. However, we&#8217;ve already stated that we want a query that retrieves records that have been marked as Deleted (in MyTable, there&#8217;s a bit field called IsDeleted that states whether or not the record has been deleted). It turns out that it&#8217;s really easy to refine these queries. In the next example, we are going to provide methods that refine the original query further and further. We want a method that gets active products, and another method that gets active customers.</p>
<pre>protected virtual IQueryable&#60;MyTable&#62; GetAllLiveItems()
{
  IQueryable&#60;MyTable&#62; query = GetAll();
  query = from myTable in query
          where myTable.IsDeleted == false
          select myTable;
}  public List&#60;MyTable&#62; GetActiveProducts(string name)
{
  IQueryable&#60;MyTable&#62; query = GetAllLiveItems();
  query = from myTable in query
          where myTable.ProductName == name
          select myTable;
  return query.ToList&#60;MyTable&#62;();
}  public List&#60;MyTable&#62; GetActiveCustomers(string name)
{
  IQueryable&#60;MyTable&#62; query = GetAllLiveItems();
  query = from myTable in query
          where myTable.CustomerName == name
          select myTable;
  return query.ToList&#60;MyTable&#62;();
}</pre>
<p>I know, the table normalisation sucks big time, but this is intended to highlight how the queries have been refined. As you can see, the GetAllLiveItems method refines the original GetAll query so that it retrieves records that haven&#8217;t been deleted. The GetActiveCustomers and GetActiveProducts queries take the query from GetAllLiveItems and refine it further still to return the appropriate list. It&#8217;s this ability to refine and extend broad stroke queries that, in my mind, opens Linq up as a real rapid database application development tool.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Extending Linq.]]></title>
<link>http://peteohanlon.wordpress.com/2008/01/04/extending-linq/</link>
<pubDate>Fri, 04 Jan 2008 12:47:33 +0000</pubDate>
<dc:creator>peteohanlon</dc:creator>
<guid>http://peteohanlon.wordpress.com/2008/01/04/extending-linq/</guid>
<description><![CDATA[Sorry for the delay in continuing with the discussions on regular expressions, but I got a little si]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Sorry for the delay in continuing with the discussions on regular expressions, but I got a little sidetracked with the upgrade to Visual Studio 2008 (.NET 3.5), and all the &#8220;goodies&#8221; that it brings to you. For the moment I&#8217;m going to be putting the discussion on regular expressions to one side. I will get back to them but, for the moment, I want to take you on a journey into .NET 3.5.</p>
<p>Possibly the biggest headline in .NET 3.5 is the introduction of Linq. I have to admit that I was highly skeptical about how useful it will actually be in the &#8220;real world&#8221;, but having played around with it for a little while I have to admit that I&#8217;m actually quite impressed. It&#8217;s a well thought out area that actually does do a lot to increase productivity. Now, in this entry I&#8217;m not going to delve into the internals of Linq and how to use it. Instead, I&#8217;m going to talk about a feature of .NET 3.5 and how it can be used to &#8220;extend&#8221; the behaviour of Linq. Specifically, we&#8217;re going to look at how to use Extension Methods to add the ability to return a DataSet and DataTable from Linq in the same way you&#8217;d return a generic list.</p>
<p>The following code shows what you actually need to do to extend the IQueryable object in Linq. For the moment, don&#8217;t worry about what <strong>IQueryable</strong> actually does &#8211; once you&#8217;ve used Linq for a little while it becomes apparent what this interface is for, and where it fits into the big Linq picture.</p>
<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient; namespace LinqTesting
{
 /// &#60;summary&#62;
 /// This class contains miscellaneous extension methods for Linq to Sql.
 /// &#60;/summary&#62;
 public static class LinqDataExtensions
 {
  /// &#60;summary&#62;
  /// Add the ability to return a DataTable based on a particular query
  /// to a queryable object.
  /// &#60;/summary&#62;
  /// &#60;param name="extenderItem"&#62;The IQueryable object to extend.&#60;/param&#62;
  /// &#60;param name="query"&#62;The query to execute.&#60;/param&#62;
  /// &#60;param name="tableName"&#62;The name of the datatable to be added.&#60;/param&#62;
  /// &#60;returns&#62;The populated DataTable.&#60;/returns&#62;
  public static DataTable ToDataTable(this IQueryable extenderItem,
    DbCommand query,
    string tableName)
  {
    if (query == null)
    {       throw new ArgumentNullException("query");
    }
    SqlCommand cmd = (SqlCommand)query;
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.SelectCommand = cmd;
    DataTable dt = new DataTable(tableName);
    try
    {
    cmd.Connection.Open();
    adapter.Fill(dt);
    }
    finally
    {
    cmd.Connection.Close();     }
    return dt;
  }
  /// &#60;summary&#62;
  /// Add the ability to return a DataSet based on a particular query
  /// to a queryable object.
  /// &#60;/summary&#62;
  /// &#60;param name="extenderItem"&#62;The IQueryable object to extend.&#60;/param&#62;
  /// &#60;param name="query"&#62;The query to execute.&#60;/param&#62;
  /// &#60;param name="tableName"&#62;The name of the DataTable to be added.&#60;/param&#62;
  /// &#60;returns&#62;The populated dataset.&#60;/returns&#62;
  public static DataSet ToDataSet(this IQueryable extenderItem,
    DbCommand query,
    string tableName)
  {
    if (query == null)
    {
    throw new ArgumentNullException("query");
    }
    return ToDataSet(extenderItem, query, null, tableName);
  }   /// &#60;summary&#62;
  /// Add the ability to return a dataset based on a particular query
  /// to a queryable object.
  /// &#60;/summary&#62;
  /// &#60;param name="extenderItem"&#62;The IQueryable object to extend.&#60;/param&#62;
  /// &#60;param name="query"&#62;A generic dictionary containing the
  /// query to execute along with the name of the table to add it to.&#60;/param&#62;
  /// &#60;returns&#62;The populated dataset.&#60;/returns&#62;
  public static DataSet ToDataSet(this IQueryable extenderItem,
    Dictionary&#60;string, DbCommand&#62; query)
  {
    if (query == null)
    {
    throw new ArgumentNullException("query");
    }
    if (query.Count == 0)
    {
    throw new ArgumentException("query");
    }
    return ToDataSet(extenderItem, query, null);
  }   /// &#60;summary&#62;
  /// Add the ability to return a dataset based on a particular query   /// to a queryable object.
  /// &#60;/summary&#62;
  /// &#60;param name="extenderItem"&#62;The IQueryable object to extend.&#60;/param&#62;
  /// &#60;param name="query"&#62;A generic dictionary containing the
  /// query to execute along with the name of the table to add it to.&#60;/param&#62;
  /// &#60;param name="dataSet"&#62;An optional DataSet. This allows application
  /// to add multiple tables to the dataset.&#60;/param&#62;
  /// &#60;returns&#62;The populated dataset.&#60;/returns&#62;
  public static DataSet ToDataSet(this IQueryable extenderItem,
    Dictionary&#60;string,
    DbCommand&#62; query,
    DataSet dataSet)
  {
    if (query == null)
    {
    throw new ArgumentNullException("query");
    }
    if (query.Count == 0)
    {
    throw new ArgumentException("query");
    }
    if (dataSet == null)       dataSet = new DataSet();  

    foreach (KeyValuePair&#60;string, DbCommand&#62; kvp in query)
    {
      dataSet = LinqDataExtensions.ToDataSet(extenderItem,
        kvp.Value,
        dataSet,
        kvp.Key);
    }
    return dataSet;
  }   /// &#60;summary&#62;
  /// Add the ability to return a dataset based on a particular
  /// query to a queryable object.
  /// &#60;/summary&#62;
  /// &#60;param name="extenderItem"&#62;The IQueryable object to extend.&#60;/param&#62;
  /// &#60;param name="query"&#62;The query to execute.&#60;/param&#62;
  /// &#60;param name="dataSet"&#62;An optional DataSet. This allows
  /// application to add multiple tables to the dataset.&#60;/param&#62;
  /// &#60;param name="tableName"&#62;The name of the DataTable to be added.&#60;/param&#62;
  /// &#60;returns&#62;The populated dataset.&#60;/returns&#62;
  public static DataSet ToDataSet(this IQueryable extenderItem,
    DbCommand query,
    DataSet dataSet,
    string tableName)
  {
    if (query == null)
    {
    throw new ArgumentNullException("query");
    }
    if (dataSet == null)
      dataSet = new DataSet();
    DataTable tbl = LinqDataExtensions.ToDataTable(extenderItem,
      query,
      tableName);
    if (tbl != null)
    {
      if (dataSet.Tables.Contains(tableName))
        dataSet.Tables.Remove(tableName);
      dataSet.Tables.Add(tbl);
    }
    return dataSet;
  }
 }
}</pre>
<p>A couple of points to note about the class. Extension methods have to be in static classes, and they have to be static methods. In order to note what class is being extended, you use the &#8220;this&#8221; keyword before the first parameter. The code itself is fairly self explanatory and doesn&#8217;t do anything clever. The clever bit actually occurs in the Linq side. Here&#8217;s an example:</p>
<pre>public DataSet GetDataSet()
{
    IQueryable q = GetAllQuery();
    return q.ToDataSet(context.GetCommand(GetAllQuery()), null, "MyTable");
} 

private IQueryable&#60;MyTable&#62; GetAllQuery()
{
    IQueryable&#60;MyTable&#62; q = from p in context.MyTables
                        select p;     return q;
}</pre>
<p>The context is the DataContext item that you will create when you import the tables using Visual Studio. And that&#8217;s it. Using similar techniques you can extend other parts of Linq as you see fit.</p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
