<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title>
			DigitallyCreated Blog
			(Tagged: ".NET")
				
		</title>
		<link>http://www.digitallycreated.net/Blog/Tags/.NET</link>
		<atom:link href="http://www.digitallycreated.net/Blog/Tags/.NET/Rss" rel="self" type="application/rss+xml" />
		<description>
			Daniel Chambers' adventures in the world of software development and beyond.
			
			
				This feed will only contain blogs that are tagged with ".NET".
			
		</description>
		<lastBuildDate>Sun, 05 Feb 2012 12:41:49 GMT</lastBuildDate>
		
		
			<item>
				<title>Performing Date &amp; Time Arithmetic Queries using Entity Framework v1</title>
				<link>http://www.digitallycreated.net/Blog/56/performing-date-and-time-arithmetic-queries-using-entity-framework-v1</link>
				<guid isPermaLink="false">DigitallyCreated Blog ID: 56</guid>
				<dc:creator>Daniel Chambers</dc:creator>
				<comments>http://www.digitallycreated.net/Blog/56/performing-date-and-time-arithmetic-queries-using-entity-framework-v1#Comments</comments>
				<slash:comments>0</slash:comments>
				<pubDate>Mon, 07 Jun 2010 15:21:31 GMT</pubDate>
				
				
					<category>Software Development</category>
				
				
				<description>
					&lt;p&gt;If one is writing legacy code in .NET 3.5 SP1’s Entity Framework v1 (yes, your brand new code has now been put into the legacy category by .NET 4 :( ), one will find a severe lack of any date &amp;amp; time arithmetic ability. If you look at LINQ to Entities, you will see &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb738681%28VS.90%29.aspx&quot;&gt;no date &amp;amp; time arithmetic methods are recognised&lt;/a&gt;. And if you look at the canonical functions that Entity SQL provides, you will notice &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb738563%28VS.90%29.aspx&quot;&gt;a severe lack of any date &amp;amp; time arithmetic functions&lt;/a&gt;. Thankfully, this strangely missing functionality in canonical ESQL &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb738563(VS.100).aspx&quot;&gt;has been resolved as of .NET 4&lt;/a&gt;; however, that doesn’t help those of us who haven’t yet upgraded to Visual Studio 2010! Thankfully, all is not lost: there is a solution that only sucks a little bit.&lt;/p&gt;  &lt;p&gt;Date &amp;amp; time arithmetic is a pretty necessary ability. Imagine the following simplified scenario, where one has a “Contract” entity that defines a business contract that starts at a certain date and lasts for a duration:&lt;/p&gt;  &lt;div style=&quot;width: 208px&quot; class=&quot;ImageBox CentredContentBox&quot;&gt;&lt;img title=&quot;Contract Entity Diagram&quot; alt=&quot;Contract Entity Diagram&quot; src=&quot;http://www.digitallycreated.net/Content/Public/Blog/ContractEntity_5b925bce-4bbe-4354-ad35-011f75aea949.gif&quot; width=&quot;208&quot; height=&quot;204&quot; /&gt; &lt;/div&gt;  &lt;p&gt;Imagine that you need to perform a query that finds all Contracts that were active on a specific date. You may think of performing a LINQ to Entities query that looks like this:&lt;/p&gt;  &lt;pre class=&quot;brush: csharp;&quot;&gt;IQueryable&amp;lt;Contract&amp;gt; contracts = 
    from contract in Contracts
    where activeOnDate &amp;gt;= contract.StartDate &amp;amp;&amp;amp;
          activeOnDate &amp;lt; contract.StartDate.AddMonths(contract.Duration)
    select contract&lt;/pre&gt;

&lt;p&gt;However, this is not supported by LINQ to Entities and you’ll get a NotSupportedException. With canonical ESQL missing any defined date &amp;amp; time arithmetic functions, it seems we are left without a recourse.&lt;/p&gt;

&lt;p&gt;However, if one digs around in MSDN, one may stumble across the fact that the SQL Server Entity Framework provider defines some &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb399545%28VS.90%29.aspx&quot;&gt;provider-specific ESQL functions&lt;/a&gt; with which one can use to do date &amp;amp; time arithmetic. So we can write an ESQL query to get the functionality we wish:&lt;/p&gt;

&lt;pre class=&quot;brush: csharp;&quot;&gt;const string eSqlQuery = @&amp;quot;SELECT VALUE c FROM Contracts AS c
                           WHERE @activeOnDate &amp;gt;= c.StartDate
                           AND @activeOnDate &amp;lt; SqlServer.DATEADD('months', c.Duration, c.StartDate)&amp;quot;;

ObjectQuery&amp;lt;Contract&amp;gt; contracts = 
    context.CreateQuery&amp;lt;Contract&amp;gt;(eSqlQuery, new ObjectParameter(&amp;quot;activeOnDate&amp;quot;, activeOnDate));&lt;/pre&gt;

&lt;p&gt;Note the use of the SqlServer.DATEADD ESQL function. The “SqlServer” bit is specifying the SQL Server provider’s specific namespace. Obviously this approach has some disadvantages: it’s not as nice as using LINQ to Entities, and it’s also not database provider agnostic (so if you’re using Oracle you’ll need to see whether your Oracle provider has something like this). However, the alternatives are either to write SQL manually (negating the usefulness of Entity Framework) or to download all the entities into local memory and use LINQ to Objects (almost never, ever an acceptable option!).&lt;/p&gt;

&lt;p&gt;Notice that using the CreateQuery function to create the query from ESQL returned an ObjectQuery&amp;lt;T&amp;gt; (which implements IQueryable&amp;lt;T&amp;gt;)? This means that you can now use LINQ to Entities to change that query. For example, what if we wanted to perform some further filtering that can be customised by the user (the user’s filtering preferences are set in the ContractFilterSettings class in the below example):&lt;/p&gt;

&lt;pre class=&quot;brush: csharp;&quot;&gt;private ObjectQuery&amp;lt;Contract&amp;gt; CreateFilterSettingsAsQueryable(ContractFilterSettings filterSettings, MyEntitiesContext context)
{
    IQueryable&amp;lt;Contract&amp;gt; query = context.Contracts;

    if (filterSettings.ActiveOnDate != null)
    {
        const string eSqlQuery = @&amp;quot;SELECT VALUE c FROM Contracts AS c
                                   WHERE @activeOnDate &amp;gt;= c.StartDate
                                   AND @activeOnDate &amp;lt; SqlServer.DATEADD('months', c.Duration, c.StartDate)&amp;quot;;
        query = context.CreateQuery&amp;lt;Contract&amp;gt;(eSqlQuery, new ObjectParameter(&amp;quot;activeOnDate&amp;quot;, filterSettings.ActiveOnDate));
    }
    if (filterSettings.SiteId != null)
        query = query.Where(c =&amp;gt; c.SiteID == filterSettings.SiteId);
    if (filterSettings.ContractNumber != null)
        query = query.Where(c =&amp;gt; c.ContractNumber == filterSettings.ContractNumber);
    
    return (ObjectQuery&amp;lt;Contract&amp;gt;)query;
}&lt;/pre&gt;

&lt;p&gt;Being able to continue to use LINQ to Entities after creating the initial query in ESQL means that you can have the best of both worlds (forgetting the fact that we ought to be able to do date &amp;amp; time arithmetic in LINQ to Entities in the first place!). Note that although you can start a query in ESQL and then add to it with LINQ to Entities, you cannot start a query in LINQ to Entities and add to it with ESQL, hence why the ActiveOnDate filter setting was done first.&lt;/p&gt;

&lt;p style=&quot;text-decoration: line-through&quot;&gt;For those who use .NET 4, unfortunately you’re still stuck with being unable to do date &amp;amp; time arithmetic with LINQ to Entities by default (&lt;a href=&quot;http://blogs.msdn.com/alexj/&quot;&gt;Alex James&lt;/a&gt; told me on Twitter a while back that this was purely because of time constraints, not because they are evil or something :) ). However, you get &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb738563(VS.100).aspx&quot;&gt;canonical ESQL functions&lt;/a&gt; that are provider independent (so instead of using SqlServer.DATEADD above, you’d use AddMonths). If you really want to use LINQ to Entities (which is not surprising at all), you can create ESQL snippets in your model (“Model Defined Functions”) and then create annotated method stubs which Entity Framework will recognise when you use them inside a LINQ to Entities query expression tree. For more information &lt;a href=&quot;http://blogs.msdn.com/b/efdesign/archive/2009/01/07/model-defined-functions.aspx&quot;&gt;see this post on the Entity Framework Design blog&lt;/a&gt;, and &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/dd456857.aspx&quot;&gt;this MSDN article&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;EDIT: &lt;a href=&quot;http://blogs.msdn.com/b/diego/&quot;&gt;Diego Vega&lt;/a&gt; kindly &lt;a href=&quot;http://twitter.com/divega/status/15693189127&quot;&gt;pointed out to me on Twitter&lt;/a&gt; that, in fact, Entity Framework 4 comes with some methods you can mix into your LINQ to Entities queries to call on EF v4’s new canonical date &amp;amp; time ESQL functions. Those methods (as well as a bunch of others) &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.data.objects.entityfunctions_members.aspx&quot;&gt;can be found in the EntityFunctions class&lt;/a&gt; as static methods. Thanks Diego!&lt;/p&gt;
				</description>
			</item>
			
		
	</channel>
</rss>
