<?xml version="1.0" encoding="UTF-8"?>
<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/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Mehroz's Experiments</title>
	<atom:link href="http://smehrozalam.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://smehrozalam.wordpress.com</link>
	<description>My computational experiments, mostly related to .Net and SQL server, to be posted here</description>
	<lastBuildDate>Thu, 29 Oct 2009 17:58:33 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='smehrozalam.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/74f848eea64ca2033a64470b2fb78878?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Mehroz's Experiments</title>
		<link>http://smehrozalam.wordpress.com</link>
	</image>
			<item>
		<title>Silverlight: Update service reference for a WCF service generating empty class</title>
		<link>http://smehrozalam.wordpress.com/2009/10/29/silverlight-update-service-reference-for-a-wcf-service-generting-empty-class/</link>
		<comments>http://smehrozalam.wordpress.com/2009/10/29/silverlight-update-service-reference-for-a-wcf-service-generting-empty-class/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 17:53:42 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[silverlight]]></category>
		<category><![CDATA[service reference]]></category>
		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=717</guid>
		<description><![CDATA[My Visual Studio sometimes goes angry. I had a Silverlight 2 &#8211; WCF &#8211; LINQToSQL application that I recently  converted to Silverlight 3. I noticed that sometimes the Update Service Reference does not function properly and instead blanks out the generated reference.cs. It broke once again today and I decided to blog it. Here [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=717&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>My Visual Studio sometimes goes angry. I had a Silverlight 2 &#8211; WCF &#8211; LINQToSQL application that I recently  converted to Silverlight 3. I noticed that sometimes the <code>Update Service Reference</code> does not function properly and instead blanks out the generated <code>reference.cs</code>. It broke once again today and I decided to blog it. Here are the contents of <code>Error</code> window when such abnormal activity happens:</p>
<p><code>Custom tool error: Failed to generate code for the service reference '..'.  Please check other error and warning messages for details.<br />
</code></p>
<p>The warning tab may have many warnings, some of which are:</p>
<p><code>Custom tool warning: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.</code></p>
<p><code>Custom tool warning: The type 'System.Collections.ObjectModel.ObservableCollection`1' could not be found.  Ensure that the assembly containing the type is referenced.  If the assembly is part of the current development project, ensure that the project has been built.</code></p>
<p><code>Custom tool warning: Cannot import wsdl:portType<br />
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter<br />
Error: Exception has been thrown by the target of an invocation.<br />
XPath to Error Source: //wsdl:definitions[@targetNamespace='']/wsdl:portType[@name=..]</code></p>
<p><code>Custom tool warning: Cannot import wsdl:port<br />
Detail: There was an error importing a wsdl:binding that the wsdl:port is dependent on.<br />
XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='..']/wsdl:binding[@name='..']</code></p>
<p><code>Custom tool warning: No endpoints compatible with Silverlight 3 were found. The generated client class will not be usable unless endpoint information is provided via the constructor.</code></p>
<p>Ok. Looks like something is wrong with the Observable Collection reference. This was further confirmed when I brought up the service configuration window (by right clicking the WCF service and selecting <code>Configure Service Reference</code>), and noticed that the <code>ObservableCollection</code> collection type has been replaced by <code>{ Custom }</code> :</p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/10/service-reference-incorrect.jpg"><img class="alignnone size-medium wp-image-737" title="service-reference-incorrect" src="http://smehrozalam.files.wordpress.com/2009/10/service-reference-incorrect.jpg?w=300&#038;h=281" alt="service-reference-incorrect" width="300" height="281" /></a></p>
<p>For comparison, here&#8217;s the normal screenshot for this window:</p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/10/service-reference-correct.jpg"><img class="alignnone size-medium wp-image-738" title="service-reference-correct" src="http://smehrozalam.files.wordpress.com/2009/10/service-reference-correct.jpg?w=300&#038;h=281" alt="service-reference-correct" width="300" height="281" /></a></p>
<p>To get rid of this and regenerate service proxy properly, I had to remove the <strong>Reuse types in all referenced assemblies</strong> (or at least System assembly).</p>
<p>So, if such behavior ever happen to you, try to update the service reference after unchecking the reuse types checkbox. Once done, you can recheck the option and update your service reference again.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/717/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/717/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/717/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/717/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/717/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/717/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/717/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/717/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/717/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/717/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=717&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/10/29/silverlight-update-service-reference-for-a-wcf-service-generting-empty-class/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/10/service-reference-incorrect.jpg?w=300" medium="image">
			<media:title type="html">service-reference-incorrect</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/10/service-reference-correct.jpg?w=300" medium="image">
			<media:title type="html">service-reference-correct</media:title>
		</media:content>
	</item>
		<item>
		<title>T-SQL: Using result of a dynamic SQL query in a variable or table</title>
		<link>http://smehrozalam.wordpress.com/2009/10/14/t-sql-using-result-of-a-dynamic-sql-query-in-a-variable-or-table/</link>
		<comments>http://smehrozalam.wordpress.com/2009/10/14/t-sql-using-result-of-a-dynamic-sql-query-in-a-variable-or-table/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 10:27:10 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[T-SQL]]></category>
		<category><![CDATA[dynamic sql]]></category>
		<category><![CDATA[exec]]></category>
		<category><![CDATA[sp_executessql]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[table]]></category>
		<category><![CDATA[table variable]]></category>
		<category><![CDATA[temporary table]]></category>
		<category><![CDATA[tsql]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=688</guid>
		<description><![CDATA[Although, not a recommended practice, but sometimes we have to write our queries using dynamic SQL. In such situations, it is generally needed to fetch the result (scalar or tabular) of dynamic SQL into the main (non-dynamic) query. This is not straight forward because dynamic SQL runs in its own scope and we cannot access [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=688&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Although, not a recommended practice, but sometimes we have to write our queries using dynamic SQL. In such situations, it is generally needed to fetch the result (scalar or tabular) of dynamic SQL into the main (non-dynamic) query. This is not straight forward because dynamic SQL runs in its own scope and we cannot access the variables defined in main query. This post presents a few approaches to consume the result of a dynamic SQL query:</p>
<p><strong>sp_ExecuteSql stored procedure</strong></p>
<p>This is the most generic and powerful method of invoking dynamic SQL since it allows us to write a parameterized dynamic query with input/output parameters. Here’s a simple example of using <a href="http://msdn.microsoft.com/en-us/library/aa933299%28SQL.80%29.aspx">sp_executesql</a> to consume the result of a dynamic SQL query:</p>
<pre class="brush: sql;">

declare @today datetime
exec sp_executesql
    N'Select @internalVariable = GetDate()', --dynamic query
    N'@internalVariable DateTime output', --query parameters
    @internalVariable = @today output --parameter mapping
select @today
</pre>
<p><strong>Table variables and Temporary tables</strong></p>
<p>This method is used when we want to get a tabular result set from our dynamic query. Here’s an example to get the result of a dynamically created SQL query by using table variables:</p>
<pre class="brush: sql;">

declare @myTable table
(
    DatabaseName nvarchar(256),
    DatabaseID int,
    CreateDate datetime
)

insert into @myTable
    exec (N'select name, database_id, create_date from sys.databases') --dynamic query

select * from @myTable
</pre>
<p>Here’s the same example that uses a temporary table to fetch the result set of a dynamic SQL query:</p>
<pre class="brush: sql;">

create table #myTable
(
    DatabaseName nvarchar(256),
    DatabaseID int,
    CreateDate datetime
)

insert into #myTable
    exec (N'select name, database_id, create_date from sys.databases') --dynamic query

select * from #myTable
drop table #myTable
</pre>
<p>Since temporary tables have physical existence so we can refer to the temporary table inside our dynamic SQL query as well. Here’s an example illustrating this technique:</p>
<pre class="brush: sql;">

create table #myTable
(
    DatabaseName nvarchar(256),
    DatabaseID int,
    CreateDate datetime
)

--dynamic query
exec sp_executesql
    N'insert into #myTable
        select name, database_id, create_date from sys.databases'

select * from #myTable
drop table #myTable
</pre>
<p>Temporary tables or Table variables can also be used to fetch the result of a stored procedure. Notice that for saving this result, the columns of table variable/temporary table must match with the result of stored procedure. That is, we need to take &#8220;ALL&#8221; the columns. Here&#8217;s an example that grabs the result set from a stored procedure into a table variable.</p>
<pre class="brush: sql;">

declare @myTable table
(
    ServerName nvarchar(256),
    NetworkName nvarchar(256),
    Status nvarchar(4000),
    ID int,
    Collation nvarchar(256),
    ConnectTimeOut int,
    QueryTimeOut int
)

insert into @myTable
    exec sp_helpserver

select * from @myTable
</pre>
<p>Also, here&#8217;s an example to get result of a stored procedure using temporary table:</p>
<pre class="brush: sql;">

create table #myTable
(
    ServerName nvarchar(256),
    NetworkName nvarchar(256),
    Status nvarchar(4000),
    ID int,
    Collation nvarchar(256),
    ConnectTimeOut int,
    QueryTimeOut int
)

insert into #myTable
    exec sp_helpserver

select * from #myTable
drop table #myTable
</pre>
<p>Thats all from me. Let me know if you have any more solutions.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/688/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/688/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/688/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/688/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/688/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/688/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/688/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/688/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/688/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/688/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=688&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/10/14/t-sql-using-result-of-a-dynamic-sql-query-in-a-variable-or-table/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>
	</item>
		<item>
		<title>LINQ to SQL: Visual Studio designer failed to autogenerate .designer.cs data classes</title>
		<link>http://smehrozalam.wordpress.com/2009/10/05/linq-to-sql-visual-studio-designer-failed-to-autogenerate-designer-cs-data-classes/</link>
		<comments>http://smehrozalam.wordpress.com/2009/10/05/linq-to-sql-visual-studio-designer-failed-to-autogenerate-designer-cs-data-classes/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 17:59:59 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[linq]]></category>
		<category><![CDATA[linq to sql]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[vs designer]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=691</guid>
		<description><![CDATA[I had a really strange observation today. I opened one of my LINQ to SQL dbml files, made some changes, and then saved it back to have my designer generated data classes updated. But instead of reflecting my changes in the .designer.cs class, Visual studio deleted that designer generated file. I tried several times but [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=691&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I had a really strange observation today. I opened one of my LINQ to SQL dbml files, made some changes, and then saved it back to have my designer generated data classes updated. But instead of reflecting my changes in the .designer.cs class, Visual studio deleted that designer generated file. I tried several times but every time LINQ designer was deleting my autogenerated data classes. I googled and found an amazing answer by Marc Gravell at <a href="http://stackoverflow.com/questions/515089/linq-to-sql-designer-not-working">this</a> stackoverflow question. The position of using statements was the source of problem!!! I had extended the LINQ generated partial classes and the first statement in that file was &#8220;using System&#8221;. I removed that and the VS designer was happy again.</p>
<p>So for anyone else that experiences the same problem, try moving your using statements after the namespace declaration. For example, if you have extended your data context or any other data class like this:</p>
<pre class="brush: csharp;">
using System;
namespace MyNamespace
{
    partial class MyDataContext
    {
        ...
    }
    ...
}
</pre>
<p>Try rearranging the declarations like this: </p>
<pre class="brush: csharp;">
namespace MyNamespace
{
    using System;

    partial class MyDataContext
    {
        ...
    }
    ...
}
</pre>
<p>Hope this post helps someone else as well.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/691/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/691/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/691/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/691/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/691/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=691&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/10/05/linq-to-sql-visual-studio-designer-failed-to-autogenerate-designer-cs-data-classes/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>
	</item>
		<item>
		<title>TSQL Challenge 12: Completing sequence by inserting missing rows</title>
		<link>http://smehrozalam.wordpress.com/2009/09/03/tsql-challenge-12-completing-sequence-by-inserting-missing-rows/</link>
		<comments>http://smehrozalam.wordpress.com/2009/09/03/tsql-challenge-12-completing-sequence-by-inserting-missing-rows/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 18:24:51 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[T-SQL]]></category>
		<category><![CDATA[cte]]></category>
		<category><![CDATA[missing]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[sequence]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[tsql challenge]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=644</guid>
		<description><![CDATA[TSQL Challenge 12 was a relatively easier one. The participants were given month-wise score values and were asked to complete the sequence by creating entries for missing month.
Here&#8217;s the sample input:

YearMonth   Score
----------- -----------
200903      100
200803      95
200802      99
200801      100
200711      100

And here&#8217;s the desired output. Notice that the score of last month is replicated in each of the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=644&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://beyondrelational.com/blogs/tc/archive/2009/08/09/tsql-challenge-12-build-sequential-ranges-of-dates-with-propagation-to-missing-values.aspx">TSQL Challenge 12</a> was a relatively easier one. The participants were given month-wise score values and were asked to complete the sequence by creating entries for missing month.</p>
<p>Here&#8217;s the sample input:</p>
<pre class="brush: xml;">
YearMonth   Score
----------- -----------
200903      100
200803      95
200802      99
200801      100
200711      100
</pre>
<p>And here&#8217;s the desired output. Notice that the score of last month is replicated in each of the missing rows:</p>
<pre class="brush: xml;">
YearMonth   Score
----------- -----------
200908      100
200907      100
200906      100
200905      100
200904      100
200903      100
200902      95
200901      95
200812      95
200811      95
200810      95
200809      95
200808      95
200807      95
200806      95
200805      95
200804      95
200803      95
200802      99
200801      100
200712      100
200711      100
</pre>
<p>The script to generate sample data is provided below:</p>
<pre class="brush: sql;">
DECLARE @Scores TABLE
(
	YearMonth	INT,
	Score		INT
)

INSERT @Scores VALUES(200903, 100)
INSERT @Scores VALUES(200803, 95)
INSERT @Scores VALUES(200802, 99)
INSERT @Scores VALUES(200801 ,100)
INSERT @Scores VALUES(200711, 100)
</pre>
<p><strong>Solution</strong></p>
<p>I once blogged about creating a sequence of numbers/dates using a recursive CTE in <a href="http://smehrozalam.wordpress.com/2009/06/09/t-sql-using-common-table-expressions-cte-to-generate-sequences/">this</a> post. The same technique can be used here. However, since the <code>YearMonth</code> column in the sample data is integer, we have two choices:</p>
<ol>
<li>Convert it to DateTime and apply T-SQL DateTime functions</li>
<li>Leave it as Integer and apply some intelligent arithmetic</li>
</ol>
<p>I am providing both the solutions here. Note that the first solution will be slower due to overhead of casting and applying T-SQL scalar functions.</p>
<p><strong>The first solution: Converting to DateTime</strong></p>
<pre class="brush: sql;">
;with cte as
(
    select score, Cast(Cast(YearMonth as varchar)+'01' as datetime) as dateVal
        from @scores
    union all
    select score, dateadd(month, 1, dateval)
        from cte
        where not exists
            --the resultant YearMonth value should not lie in the original table
            ( select 1 from @scores s where s.YearMonth = cast( left(convert(varchar, dateadd(month, 1, cte.dateval), 112), 6) as int) )
            --stop at current month
            and dateadd(month, 1, cte.dateval) &lt; getdate()
)

select left(convert(varchar, dateval, 112), 6) as yearmonth, score
from cte
order by dateval desc
</pre>
<p><strong>Explanation:</strong><br />
Here I am simply converting the integer <code>YearMonth</code> column to a datetime <code>dateval</code> column by appending 01 to the end (so a <code>200901</code> becomes <code>20090101</code> that can easily be cast to a dateTime) and then finding subsequent dates by adding one month in each CTE iteration.</p>
<p><strong>The second solution: Integer Arithmetic</strong></p>
<pre class="brush: sql;">
;with cte as
(
    select YearMonth, Score
		from @Scores
    union all
    select YearMonth + YearMonth % 100 / 12 * 88 + 1 as YearMonth, Score
        from cte
        where not exists
            --the resultant YearMonth value should not lie in the original table
            ( select s.YearMonth from @Scores s where s.YearMonth = (cte.YearMonth + cte.YearMonth % 100 / 12 * 88 + 1) )
            --stop at current month
            and cte.YearMonth &lt; month(getdate()) + year(getdate())*100
)

select *
from cte
order by YearMonth desc
</pre>
<p><strong>Explanation:</strong><br />
The important point is to increment the value of <code>YearMonth</code> correctly. So <code>200811</code> should get incremented to <code>200812</code> but <code>200812</code> should get incremented to <code>200901</code>. This isn&#8217;t difficult if we introduce a case statement like this:</p>
<p><code>YearMonth + (Case When YearMonth%100 &lt; 12 Then 1 Else 89 End)</code></p>
<p>But I wanted to do this purely using arithmetic with no <code>Case</code> statements, so I came up with this formula:</p>
<p><code>(YearMonth % 100 / 12 * 88) + 1</code></p>
<p>Note that the factor <code>(YearMonth % 100 / 12 * 88)</code> will reduce to zero for all values from January to November, i.e. from <code>200801</code> to <code>200811</code>.</p>
<p>I hope you enjoyed the solution.</p>
<p><strong>Update:</strong><br />
It was pointed out in one of the comments by Rakesh that the solution could reach the default limit of recursion which is 100. In order to avoid this, we need to add <code>option (maxrecursion 12,000)</code> in the final select statement. Then, we can have 10,000 years missing between two adjacent entries. Thanks, Rakesh. </p>
<pre class="brush: sql;">
...
select *
from cte
order by YearMonth desc
option (maxrecursion 12,000)
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/644/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/644/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/644/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/644/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/644/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=644&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/09/03/tsql-challenge-12-completing-sequence-by-inserting-missing-rows/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>
	</item>
		<item>
		<title>Avoiding hard-coded strings while raising or handling PropertyChanged event</title>
		<link>http://smehrozalam.wordpress.com/2009/08/26/avoiding-string-while-raising-or-handling-propertychanged-event/</link>
		<comments>http://smehrozalam.wordpress.com/2009/08/26/avoiding-string-while-raising-or-handling-propertychanged-event/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 09:09:46 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[dotnet]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[Expression Tree]]></category>
		<category><![CDATA[INotifyPropertyChanged]]></category>
		<category><![CDATA[mvvm]]></category>
		<category><![CDATA[PropertyChaged]]></category>
		<category><![CDATA[PropertyChangedEventArgs]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=647</guid>
		<description><![CDATA[While developing WPF/Silverlight applications, and more specifically while following the Model-View-ViewModel (MVVM) pattern we will find ourselves implementing INotifyProprertyChanged most of the times. The default implementation of PropertyChanged event takes the property name as string in the PropertyChangedEventArgs which is not much robust. There are several ways to address the issue:

Use reflection to verify that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=647&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>While developing WPF/Silverlight applications, and more specifically while following the Model-View-ViewModel (MVVM) pattern we will find ourselves implementing <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(VS.95).aspx">INotifyProprertyChanged</a> most of the times. The default implementation of <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged(VS.95).aspx">PropertyChanged</a> event takes the property name as string in the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.propertychangedeventargs(VS.95).aspx">PropertyChangedEventArgs</a> which is not much robust. There are several ways to address the issue:</p>
<ul>
<li>Use reflection to verify that the property actually exists, as demonstrated once by <a href="http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/">Josh Smith</a>.</li>
<li>Use Injection using some Aspect Oriented Programming framework, like <a href="http://www.postsharp.org/">PostSharp</a></li>
<li>Use Expression Trees as described by <a href="http://michaelsync.net/2009/04/09/silverlightwpf-implementing-propertychanged-with-expression-tree">Michael Sync</a> and <a href="http://davybrion.com/blog/2009/08/refactor-safe-implementation-of-inotifypropertychanged/">Davy Brion</a></li>
</ul>
<p>Personally, I prefer using expression trees. So, instead of writing this:</p>
<pre class="brush: csharp;">
public string MyProperty
{
    get { return this.myProperty; }
    set { this.myProperty = value; this.RaisePropertyChanged(&quot;MyProperty&quot;); }
}
</pre>
<p>We can write:</p>
<pre class="brush: csharp;">
public string MyProperty
{
    get { return this.myProperty; }
    set { this.myProperty = value; this.RaisePropertyChanged( MyObj =&gt; MyObj.MyProperty ); }
}
</pre>
<p>The same issue exists looking at the other side. When we subscribe to PropertyChanged event of an object, we get the property name again as a string. One way is to use the <code>GetPropertyName( ExpressionTree )</code> extension method from the above implementation in our <code>if</code> and <code>case</code> statements. Also, Josh nicely addressed the issue in <a href="http://joshsmithonwpf.wordpress.com/2009/07/11/one-way-to-avoid-messy-propertychanged-event-handling/">this</a> post, thus allowing us to write:</p>
<pre class="brush: csharp;">
MyClass myObject = new MyClass();
PropertyObserver&lt;MyClass&gt; observer = new PropertyObserver&lt;MyClass&gt;(myObject)
    .RegisterHandler(myObj =&gt; myObj.MyProperty1, myObj =&gt; { /* handle change in MyProperty1 */ })
    .RegisterHandler(myObj =&gt; myObj.MyProperty2, MyProperty2HandlerMethod  );
</pre>
<p>Notice that Josh used <a href="http://msdn.microsoft.com/en-us/library/system.windows.iweakeventlistener.aspx">IWeakEventListener</a> that isn&#8217;t available for Silverlight but luckily Pete O&#8217; Hanlon provided us with a Silverlight version of Josh&#8217;s work <a href="http://peteohanlon.wordpress.com/2009/07/19/its-not-that-hard-to-add-the-missing-bits-to-silverlight/">here</a>.</p>
<p>So, combining the great efforts of all these people, we are going to have a better MVVM experience.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/647/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/647/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/647/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/647/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/647/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/647/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=647&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/08/26/avoiding-string-while-raising-or-handling-propertychanged-event/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>
	</item>
		<item>
		<title>SSMS: How to restore differential backups</title>
		<link>http://smehrozalam.wordpress.com/2009/08/18/ssms-how-to-restore-differential-backups/</link>
		<comments>http://smehrozalam.wordpress.com/2009/08/18/ssms-how-to-restore-differential-backups/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 11:02:25 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[differential]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[ssms]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=631</guid>
		<description><![CDATA[There are two ways to restore a differential backup in SQL Server:

Directly use TSQL statements as described in this MSDN page
Use SQL Server Management Studio user interface as described here.

If you are using SQL Management Studio to restore differential backups, and you have restored full backups several time using SSMS, but this is your first [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=631&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>There are two ways to restore a differential backup in SQL Server:</p>
<ul>
<li>Directly use TSQL statements as described in <a href="http://msdn.microsoft.com/en-us/library/ms186858.aspx#restoring_full_n_differential_db_backups">this</a> MSDN page</li>
<li>Use SQL Server Management Studio user interface as described <a href="http://msdn.microsoft.com/en-us/library/ms175510.aspx">here</a>.</li>
</ul>
<p>If you are using SQL Management Studio to restore differential backups, and you have restored full backups several time using SSMS, but this is your first time to restore a differential backup then you are likely to encounter the following error:</p>
<p><code>Restore failed for Server 'servername'. (Microsoft.SqlServer.SmoExtended)<br />
ADDITIONAL INFORMATION:<br />
System.Data.SqlClient.SqlError: The log or differential backup cannot be restored because no files are ready to rollforward. (Microsoft.SqlServer.Smo)</code></p>
<p>This is because you tried to restore a differential backup on an available/operational/functional/running database which is not allowed.</p>
<p>In order to restore a differential backup, you will first need to restore the <strong>last full backup</strong> with <strong>NO RECOVERY</strong> option. So, in SSMS you need to select the appropriate full-backup and choose <strong>Restore With NoRecovery</strong> option from the <strong>Options</strong> page as depicted in the following screenshot.</p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/restore-full-backup-with-norecovery.jpg"><img class="alignnone size-medium wp-image-634" title="restore-full-backup-with-norecovery" src="http://smehrozalam.files.wordpress.com/2009/08/restore-full-backup-with-norecovery.jpg?w=300&#038;h=260" alt="restore-full-backup-with-norecovery" width="300" height="260" /></a></p>
<p>Once restored, the database will be shown in the Object Explorer as <strong>Restoring.</strong></p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/database-in-restore.jpg"><img class="alignnone size-full wp-image-633" title="database-in-restore" src="http://smehrozalam.files.wordpress.com/2009/08/database-in-restore.jpg?w=322&#038;h=331" alt="database-in-restore" width="322" height="331" /></a></p>
<p>Notice that the database is non-available/non-functional at this time and is waiting for a differential backup to be applied. Now, restore the appropriate differential backup and choose <strong>Restore With Recovery</strong> from the <strong>Options</strong> page:</p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/restore-differential-backup-with-recovery.jpg"><img class="alignnone size-medium wp-image-632" title="restore-differential-backup-with-recovery" src="http://smehrozalam.files.wordpress.com/2009/08/restore-differential-backup-with-recovery.jpg?w=300&#038;h=260" alt="restore-differential-backup-with-recovery" width="300" height="260" /></a></p>
<p>That’s it. You have successfully restored a differential backup.</p>
<p><span style="text-decoration:underline;"><strong>A Final Note:</strong></span></p>
<p>Note that differential backups are <strong>cumulative</strong> and each differential backup contain changes since the <strong>last full</strong> backup, <strong>not</strong> the last differential backup. So if you have a full backup of 2009-01-01 and have differential backups for each day, and you want to restore your database to 2009-01-10, then you just need to restore the full backup (with no recovery) of 2009-01-01 followed by the differential backup of 2009-01-10. For more information, read the following MSDN articles from SQL Server books online:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms181092.aspx">Differential Database Backups</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms345448.aspx">How Differential Backups Work</a></li>
</ul>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/631/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/631/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/631/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/631/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/631/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/631/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=631&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/08/18/ssms-how-to-restore-differential-backups/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/restore-full-backup-with-norecovery.jpg?w=300" medium="image">
			<media:title type="html">restore-full-backup-with-norecovery</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/database-in-restore.jpg" medium="image">
			<media:title type="html">database-in-restore</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/restore-differential-backup-with-recovery.jpg?w=300" medium="image">
			<media:title type="html">restore-differential-backup-with-recovery</media:title>
		</media:content>
	</item>
		<item>
		<title>Entity Framework: Creating a model using views instead of tables</title>
		<link>http://smehrozalam.wordpress.com/2009/08/12/entity-framework-creating-a-model-using-views-instead-of-tables/</link>
		<comments>http://smehrozalam.wordpress.com/2009/08/12/entity-framework-creating-a-model-using-views-instead-of-tables/#comments</comments>
		<pubDate>Wed, 12 Aug 2009 12:07:16 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[association]]></category>
		<category><![CDATA[entity model]]></category>
		<category><![CDATA[Relation]]></category>
		<category><![CDATA[View]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=600</guid>
		<description><![CDATA[A few days back, I created an entity model using views instead of tables. Since my physical model consisted of Views instead of tables so Entity Designer was not able to infer primary keys/relations etc and I had to create them manually. In this post, I will highlight the steps I took to create a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=600&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A few days back, I created an entity model using views instead of tables. Since my physical model consisted of Views instead of tables so Entity Designer was not able to infer primary keys/relations etc and I had to create them manually. In this post, I will highlight the steps I took to create a working entity model by hand. Please read at your own risk and feel free to contribute your ideas using the comments section.</p>
<p>Assume we have a JobWBS and a ResourceAssignment view with a One-Many relationship as depicted below:</p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/db-model.jpg"><img class="alignnone size-full wp-image-602" title="db-model" src="http://smehrozalam.files.wordpress.com/2009/08/db-model.jpg?w=541&#038;h=244" alt="db-model" width="541" height="244" /></a></p>
<p>If we try to create an &#8220;ADO.NET Entity Data Model&#8221; for the above views, Visual Studio will generate a model similar to this one.</p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/generated-model.jpg"><img class="alignnone size-full wp-image-603" title="generated-model" src="http://smehrozalam.files.wordpress.com/2009/08/generated-model.jpg?w=357&#038;h=246" alt="generated-model" width="357" height="246" /></a></p>
<p>Notice that the designer marked <strong>all </strong>fields as primary keys. We need to manually edit the generated edmx file by opening it with &#8220;XML editor&#8221;.</p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/open-with-xml-editor.jpg"><img class="alignnone size-full wp-image-604" title="open-with-xml-editor" src="http://smehrozalam.files.wordpress.com/2009/08/open-with-xml-editor.jpg?w=480&#038;h=293" alt="open-with-xml-editor" width="480" height="293" /></a></p>
<p>You will also notice the following warnings inside the edmx xml:</p>
<p><code>Errors Found During Generation:<br />
warning 6002: The table/view 'testdb.dbo.vw_JobWBS' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.</code></p>
<p><span id="more-600"></span></p>
<p>The edmx file mainly contains 3 parts (4<sup>th</sup> part is related to visual designer which is not significant for us): storage model, conceptual model and the mapping between them. You can identify each part easily as it is decorated with XML comments.</p>
<p><strong>Assigning Key Columns</strong></p>
<p>We first need to remove the non-primarykey columns from the key attributes of both entries from storage and conceptual model. For this, just remove non-primary columns within <code>&lt;Key&gt; and &lt;/Key&gt;</code> boundaries under storage model as well as conceptual model.</p>
<p><strong>Making views writable</strong></p>
<p>Another point to note is that the entity are defined with a <code>DefiningQuery</code> instead of the physical view/table. This prevents any inserts/updates to the database and if we try to do so, we will get something like:</p>
<p><code>Unable to update the EntitySet xxx because it has a DefiningQuery and no &lt;UpdateFunction&gt; element exists in the &lt;ModificationFunctionMapping&gt; element to support the current operation.</code></p>
<p>To solve this, remove the <code>&lt;DefininingQuery&gt; .. &lt;/DefiningQuery&gt;</code> block under <code>&lt;edmx:StorageModels&gt; / &lt;Schema&gt; / &lt;EntityContainer&gt; / &lt;EntitySet&gt;</code>. Then change <code>&lt;EntitySet EntityType="…" store:Type="Views" store:Schema="dbo" store:Name="…"&gt;</code> to <code>&lt;EntitySet EntityType="…" Schema="dbo"&gt;</code>.</p>
<p><strong>Adding associations</strong></p>
<p>That’s all regarding CRUD operations. Now we need to add a One-to-Many relationship between <code>JobWBS</code> and ResourceAssignment. For this, we need to open the visual designer,  add a 1-* association between <code>JobWBS</code> and <code>ResourceAssignment</code>, and map it to <code>ResourceAssignment</code> table. Then we need to remove the <code>JobNo</code> and <code>JobWBS</code> fields from our <code>ResourceAssignment</code> entity to get rid of the following error:</p>
<p><code>Non-Primary-Key column(s) [JobNo, JobWBSCode] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified.</code></p>
<p>At this point, our model is ready to be consumed via its domain context.</p>
<p><strong>Adding association to storage schema</strong></p>
<p>Notice that while working with RIA Domain Services, I found that we need to add the One-Many relation in the storage schema also, otherwise we will get the error: <code>Unable to retrieve AssociationType for association 'FK_ResourceAssignment_JobWBS'</code>. To add the association to the storage schema, add the following under <code>&lt;edmx:StorageModels&gt; / &lt;Schema&gt; / &lt;EntityContainer&gt;</code> just after the entities are defined:</p>
<pre class="brush: xml;">
          &lt;AssociationSet Name=&quot;FK_ResourceAssignment_JobWBS&quot; Association=&quot;MyModelNamespace.Store.FK_ResourceAssignment_JobWBS&quot;&gt;
            &lt;End Role=&quot;JobWBS&quot; EntitySet=&quot;JobWBS&quot; /&gt;
            &lt;End Role=&quot;ResourceAssignment&quot; EntitySet=&quot;ResourceAssignment&quot; /&gt;
          &lt;/AssociationSet&gt;
</pre>
<p>Then define the association under <code>&lt;edmx:StorageModels&gt; / &lt;Schema&gt;</code> as:</p>
<pre class="brush: xml;">
        &lt;Association Name=&quot;FK_ResourceAssignment_JobWBS&quot;&gt;
          &lt;End Role=&quot;JobWBS&quot; Type=&quot;MyModelNamespace.Store.JobWBS&quot; Multiplicity=&quot;1&quot; /&gt;
          &lt;End Role=&quot;ResourceAssignment&quot; Type=&quot;MyModelNamespace.Store.ResourceAssignment&quot; Multiplicity=&quot;*&quot; /&gt;
          &lt;ReferentialConstraint&gt;
            &lt;Principal Role=&quot;JobWBS&quot;&gt;
              &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
              &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
            &lt;/Principal&gt;
            &lt;Dependent Role=&quot;ResourceAssignment&quot;&gt;
              &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
              &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
            &lt;/Dependent&gt;
          &lt;/ReferentialConstraint&gt;
        &lt;/Association&gt;
</pre>
<p>Now our RIA domain service will not have any such complain.</p>
<p><strong>A final comment:</strong></p>
<p>Note that anytime you update the model from database, it will reset the SSDL and we will manually need to redo all the steps (related to storage model) as described above.</p>
<p>Finally, here’s the generated edmx and the modified one. You can run a compare on the two versions to see what changes we have made.</p>
<p><strong>Generated</strong></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;edmx:Edmx Version=&quot;1.0&quot; xmlns:edmx=&quot;http://schemas.microsoft.com/ado/2007/06/edmx&quot;&gt;
    &lt;!-- EF Runtime content --&gt;
    &lt;edmx:Runtime&gt;
        &lt;!-- SSDL content --&gt;
        &lt;edmx:StorageModels&gt;
            &lt;Schema Namespace=&quot;MyModelNamespace.Store&quot; Alias=&quot;Self&quot; Provider=&quot;System.Data.SqlClient&quot; ProviderManifestToken=&quot;2005&quot; xmlns:store=&quot;http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator&quot; xmlns=&quot;http://schemas.microsoft.com/ado/2006/04/edm/ssdl&quot;&gt;
                &lt;EntityContainer Name=&quot;MyModelNamespaceStoreContainer&quot;&gt;
                    &lt;EntitySet Name=&quot;JobWBS&quot; EntityType=&quot;MyModelNamespace.Store.JobWBS&quot; store:Type=&quot;Views&quot; store:Schema=&quot;dbo&quot; store:Name=&quot;JobWBS&quot;&gt;
                        &lt;DefiningQuery&gt;
                            SELECT
                            [JobWBS].[timestamp] AS [timestamp],
                            [JobWBS].[JobNo] AS [JobNo],
                            [JobWBS].[JobWBSCode] AS [JobWBSCode],
                            [JobWBS].[Description] AS [Description],
                            [JobWBS].[Level] AS [Level],
                            [JobWBS].[StartDate] AS [StartDate],
                            [JobWBS].[EndDate] AS [EndDate],
                            [JobWBS].[Duration] AS [Duration],
                            [JobWBS].[LastModified] AS [LastModified]
                            FROM [dbo].[JobWBS] AS [JobWBS]
                        &lt;/DefiningQuery&gt;
                    &lt;/EntitySet&gt;
                    &lt;EntitySet Name=&quot;ResourceAssignment&quot; EntityType=&quot;MyModelNamespace.Store.ResourceAssignment&quot; store:Type=&quot;Views&quot; store:Schema=&quot;dbo&quot; store:Name=&quot;ResourceAssignment&quot;&gt;
                        &lt;DefiningQuery&gt;
                            SELECT
                            [ResourceAssignment].[timestamp] AS [timestamp],
                            [ResourceAssignment].[AssignmentID] AS [AssignmentID],
                            [ResourceAssignment].[JobNo] AS [JobNo],
                            [ResourceAssignment].[JobWBSCode] AS [JobWBSCode],
                            [ResourceAssignment].[ResourceNo] AS [ResourceNo],
                            [ResourceAssignment].[StartDate] AS [StartDate],
                            [ResourceAssignment].[EndDate] AS [EndDate],
                            [ResourceAssignment].[HoursPerDay] AS [HoursPerDay]
                            FROM [dbo].[ResourceAssignment] AS [ResourceAssignment]
                        &lt;/DefiningQuery&gt;
                    &lt;/EntitySet&gt;
                &lt;/EntityContainer&gt;
                &lt;!--Errors Found During Generation:
      warning 6002: The table/view 'testdb.dbo.JobWBS' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.
      --&gt;
                &lt;EntityType Name=&quot;JobWBS&quot;&gt;
                    &lt;Key&gt;
                        &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
                        &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
                        &lt;PropertyRef Name=&quot;Description&quot; /&gt;
                        &lt;PropertyRef Name=&quot;Level&quot; /&gt;
                        &lt;PropertyRef Name=&quot;StartDate&quot; /&gt;
                        &lt;PropertyRef Name=&quot;EndDate&quot; /&gt;
                        &lt;PropertyRef Name=&quot;Duration&quot; /&gt;
                        &lt;PropertyRef Name=&quot;LastModified&quot; /&gt;
                    &lt;/Key&gt;
                    &lt;Property Name=&quot;timestamp&quot; Type=&quot;timestamp&quot; Nullable=&quot;false&quot; StoreGeneratedPattern=&quot;Computed&quot; /&gt;
                    &lt;Property Name=&quot;JobNo&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;JobWBSCode&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;60&quot; /&gt;
                    &lt;Property Name=&quot;Description&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;50&quot; /&gt;
                    &lt;Property Name=&quot;Level&quot; Type=&quot;int&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;StartDate&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;EndDate&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;Duration&quot; Type=&quot;decimal&quot; Nullable=&quot;false&quot; Precision=&quot;38&quot; Scale=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;LastModified&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                &lt;/EntityType&gt;
                &lt;!--Errors Found During Generation:
      warning 6002: The table/view 'testdb.dbo.ResourceAssignment' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.
      --&gt;
                &lt;EntityType Name=&quot;ResourceAssignment&quot;&gt;
                    &lt;Key&gt;
                        &lt;PropertyRef Name=&quot;AssignmentID&quot; /&gt;
                        &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
                        &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
                        &lt;PropertyRef Name=&quot;ResourceNo&quot; /&gt;
                        &lt;PropertyRef Name=&quot;StartDate&quot; /&gt;
                        &lt;PropertyRef Name=&quot;EndDate&quot; /&gt;
                        &lt;PropertyRef Name=&quot;HoursPerDay&quot; /&gt;
                    &lt;/Key&gt;
                    &lt;Property Name=&quot;timestamp&quot; Type=&quot;timestamp&quot; Nullable=&quot;false&quot; StoreGeneratedPattern=&quot;Computed&quot; /&gt;
                    &lt;Property Name=&quot;AssignmentID&quot; Type=&quot;int&quot; Nullable=&quot;false&quot; StoreGeneratedPattern=&quot;Identity&quot; /&gt;
                    &lt;Property Name=&quot;JobNo&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;JobWBSCode&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;60&quot; /&gt;
                    &lt;Property Name=&quot;ResourceNo&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;StartDate&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;EndDate&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;HoursPerDay&quot; Type=&quot;decimal&quot; Nullable=&quot;false&quot; Precision=&quot;38&quot; Scale=&quot;20&quot; /&gt;
                &lt;/EntityType&gt;
            &lt;/Schema&gt;
        &lt;/edmx:StorageModels&gt;
        &lt;!-- CSDL content --&gt;
        &lt;edmx:ConceptualModels&gt;
            &lt;Schema Namespace=&quot;MyModelNamespace&quot; Alias=&quot;Self&quot; xmlns=&quot;http://schemas.microsoft.com/ado/2006/04/edm&quot;&gt;
                &lt;EntityContainer Name=&quot;MyEntries&quot;&gt;
                    &lt;EntitySet Name=&quot;JobWBS&quot; EntityType=&quot;MyModelNamespace.JobWBS&quot; /&gt;
                    &lt;EntitySet Name=&quot;ResourceAssignment&quot; EntityType=&quot;MyModelNamespace.ResourceAssignment&quot; /&gt;
                &lt;/EntityContainer&gt;
                &lt;EntityType Name=&quot;JobWBS&quot;&gt;
                    &lt;Key&gt;
                        &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
                        &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
                        &lt;PropertyRef Name=&quot;Description&quot; /&gt;
                        &lt;PropertyRef Name=&quot;Level&quot; /&gt;
                        &lt;PropertyRef Name=&quot;StartDate&quot; /&gt;
                        &lt;PropertyRef Name=&quot;EndDate&quot; /&gt;
                        &lt;PropertyRef Name=&quot;Duration&quot; /&gt;
                        &lt;PropertyRef Name=&quot;LastModified&quot; /&gt;
                    &lt;/Key&gt;
                    &lt;Property Name=&quot;timestamp&quot; Type=&quot;Binary&quot; Nullable=&quot;false&quot; MaxLength=&quot;8&quot; FixedLength=&quot;true&quot; /&gt;
                    &lt;Property Name=&quot;JobNo&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;JobWBSCode&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;60&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;Description&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;50&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;Level&quot; Type=&quot;Int32&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;StartDate&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;EndDate&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;Duration&quot; Type=&quot;Decimal&quot; Nullable=&quot;false&quot; Precision=&quot;38&quot; Scale=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;LastModified&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                &lt;/EntityType&gt;
                &lt;EntityType Name=&quot;ResourceAssignment&quot;&gt;
                    &lt;Key&gt;
                        &lt;PropertyRef Name=&quot;AssignmentID&quot; /&gt;
                        &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
                        &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
                        &lt;PropertyRef Name=&quot;ResourceNo&quot; /&gt;
                        &lt;PropertyRef Name=&quot;StartDate&quot; /&gt;
                        &lt;PropertyRef Name=&quot;EndDate&quot; /&gt;
                        &lt;PropertyRef Name=&quot;HoursPerDay&quot; /&gt;
                    &lt;/Key&gt;
                    &lt;Property Name=&quot;timestamp&quot; Type=&quot;Binary&quot; Nullable=&quot;false&quot; MaxLength=&quot;8&quot; FixedLength=&quot;true&quot; /&gt;
                    &lt;Property Name=&quot;AssignmentID&quot; Type=&quot;Int32&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;JobNo&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;JobWBSCode&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;60&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;ResourceNo&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;StartDate&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;EndDate&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;HoursPerDay&quot; Type=&quot;Decimal&quot; Nullable=&quot;false&quot; Precision=&quot;38&quot; Scale=&quot;20&quot; /&gt;
                &lt;/EntityType&gt;
            &lt;/Schema&gt;
        &lt;/edmx:ConceptualModels&gt;
        &lt;!-- C-S mapping content --&gt;
        &lt;edmx:Mappings&gt;
            &lt;Mapping Space=&quot;C-S&quot; xmlns=&quot;urn:schemas-microsoft-com:windows:storage:mapping:CS&quot;&gt;
                &lt;EntityContainerMapping StorageEntityContainer=&quot;MyModelNamespaceStoreContainer&quot; CdmEntityContainer=&quot;MyEntries&quot;&gt;
                    &lt;EntitySetMapping Name=&quot;JobWBS&quot;&gt;
                        &lt;EntityTypeMapping TypeName=&quot;IsTypeOf(MyModelNamespace.JobWBS)&quot;&gt;
                            &lt;MappingFragment StoreEntitySet=&quot;JobWBS&quot;&gt;
                                &lt;ScalarProperty Name=&quot;timestamp&quot; ColumnName=&quot;timestamp&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;JobNo&quot; ColumnName=&quot;JobNo&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;JobWBSCode&quot; ColumnName=&quot;JobWBSCode&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;Description&quot; ColumnName=&quot;Description&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;Level&quot; ColumnName=&quot;Level&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;StartDate&quot; ColumnName=&quot;StartDate&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;EndDate&quot; ColumnName=&quot;EndDate&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;Duration&quot; ColumnName=&quot;Duration&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;LastModified&quot; ColumnName=&quot;LastModified&quot; /&gt;
                            &lt;/MappingFragment&gt;
                        &lt;/EntityTypeMapping&gt;
                    &lt;/EntitySetMapping&gt;
                    &lt;EntitySetMapping Name=&quot;ResourceAssignment&quot;&gt;
                        &lt;EntityTypeMapping TypeName=&quot;IsTypeOf(MyModelNamespace.ResourceAssignment)&quot;&gt;
                            &lt;MappingFragment StoreEntitySet=&quot;ResourceAssignment&quot;&gt;
                                &lt;ScalarProperty Name=&quot;timestamp&quot; ColumnName=&quot;timestamp&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;AssignmentID&quot; ColumnName=&quot;AssignmentID&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;JobNo&quot; ColumnName=&quot;JobNo&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;JobWBSCode&quot; ColumnName=&quot;JobWBSCode&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;ResourceNo&quot; ColumnName=&quot;ResourceNo&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;StartDate&quot; ColumnName=&quot;StartDate&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;EndDate&quot; ColumnName=&quot;EndDate&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;HoursPerDay&quot; ColumnName=&quot;HoursPerDay&quot; /&gt;
                            &lt;/MappingFragment&gt;
                        &lt;/EntityTypeMapping&gt;
                    &lt;/EntitySetMapping&gt;
                &lt;/EntityContainerMapping&gt;
            &lt;/Mapping&gt;
        &lt;/edmx:Mappings&gt;
    &lt;/edmx:Runtime&gt;
    &lt;!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) --&gt;
    &lt;edmx:Designer xmlns=&quot;http://schemas.microsoft.com/ado/2007/06/edmx&quot;&gt;
        &lt;edmx:Connection&gt;
            &lt;DesignerInfoPropertySet&gt;
                &lt;DesignerProperty Name=&quot;MetadataArtifactProcessing&quot; Value=&quot;EmbedInOutputAssembly&quot; /&gt;
            &lt;/DesignerInfoPropertySet&gt;
        &lt;/edmx:Connection&gt;
        &lt;edmx:Options&gt;
            &lt;DesignerInfoPropertySet&gt;
                &lt;DesignerProperty Name=&quot;ValidateOnBuild&quot; Value=&quot;true&quot; /&gt;
            &lt;/DesignerInfoPropertySet&gt;
        &lt;/edmx:Options&gt;
        &lt;!-- Diagram content (shape and connector positions) --&gt;
        &lt;edmx:Diagrams&gt;
            &lt;Diagram Name=&quot;MyDataModel&quot;&gt;
                &lt;EntityTypeShape EntityType=&quot;MyModelNamespace.JobWBS&quot; Width=&quot;1.5&quot; PointX=&quot;0.75&quot; PointY=&quot;0.75&quot; Height=&quot;2.41404296875&quot; IsExpanded=&quot;true&quot; /&gt;
                &lt;EntityTypeShape EntityType=&quot;MyModelNamespace.ResourceAssignment&quot; Width=&quot;1.5&quot; PointX=&quot;3.875&quot; PointY=&quot;0.75&quot; Height=&quot;2.2496956380208331&quot; IsExpanded=&quot;true&quot; /&gt;
            &lt;/Diagram&gt;
        &lt;/edmx:Diagrams&gt;
    &lt;/edmx:Designer&gt;
&lt;/edmx:Edmx&gt;
</pre>
<p><strong>Modified:</strong></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;edmx:Edmx Version=&quot;1.0&quot; xmlns:edmx=&quot;http://schemas.microsoft.com/ado/2007/06/edmx&quot;&gt;
    &lt;!-- EF Runtime content --&gt;
    &lt;edmx:Runtime&gt;
        &lt;!-- SSDL content --&gt;
        &lt;edmx:StorageModels&gt;
            &lt;Schema Namespace=&quot;MyModelNamespace.Store&quot; Alias=&quot;Self&quot; Provider=&quot;System.Data.SqlClient&quot; ProviderManifestToken=&quot;2005&quot; xmlns:store=&quot;http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator&quot; xmlns=&quot;http://schemas.microsoft.com/ado/2006/04/edm/ssdl&quot;&gt;
                &lt;EntityContainer Name=&quot;MyModelNamespaceStoreContainer&quot;&gt;
                    &lt;EntitySet Name=&quot;JobWBS&quot; EntityType=&quot;MyModelNamespace.Store.JobWBS&quot; Schema=&quot;dbo&quot;&gt;
                    &lt;/EntitySet&gt;
                    &lt;EntitySet Name=&quot;ResourceAssignment&quot; EntityType=&quot;MyModelNamespace.Store.ResourceAssignment&quot; Schema=&quot;dbo&quot;&gt;
                    &lt;/EntitySet&gt;
                    &lt;AssociationSet Name=&quot;FK_ResourceAssignment_JobWBS&quot; Association=&quot;MyModelNamespace.Store.FK_ResourceAssignment_JobWBS&quot;&gt;
                        &lt;End Role=&quot;JobWBS&quot; EntitySet=&quot;JobWBS&quot; /&gt;
                        &lt;End Role=&quot;ResourceAssignment&quot; EntitySet=&quot;ResourceAssignment&quot; /&gt;
                    &lt;/AssociationSet&gt;
                &lt;/EntityContainer&gt;
                &lt;EntityType Name=&quot;JobWBS&quot;&gt;
                    &lt;Key&gt;
                        &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
                        &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
                    &lt;/Key&gt;
                    &lt;Property Name=&quot;timestamp&quot; Type=&quot;timestamp&quot; Nullable=&quot;false&quot; StoreGeneratedPattern=&quot;Computed&quot; /&gt;
                    &lt;Property Name=&quot;JobNo&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;JobWBSCode&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;60&quot; /&gt;
                    &lt;Property Name=&quot;Description&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;50&quot; /&gt;
                    &lt;Property Name=&quot;Level&quot; Type=&quot;int&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;StartDate&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;EndDate&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;Duration&quot; Type=&quot;decimal&quot; Nullable=&quot;false&quot; Precision=&quot;38&quot; Scale=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;LastModified&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                &lt;/EntityType&gt;
                &lt;EntityType Name=&quot;ResourceAssignment&quot;&gt;
                    &lt;Key&gt;
                        &lt;PropertyRef Name=&quot;AssignmentID&quot; /&gt;
                    &lt;/Key&gt;
                    &lt;Property Name=&quot;timestamp&quot; Type=&quot;timestamp&quot; Nullable=&quot;false&quot; StoreGeneratedPattern=&quot;Computed&quot; /&gt;
                    &lt;Property Name=&quot;AssignmentID&quot; Type=&quot;int&quot; Nullable=&quot;false&quot; StoreGeneratedPattern=&quot;Identity&quot; /&gt;
                    &lt;Property Name=&quot;JobNo&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;JobWBSCode&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;60&quot; /&gt;
                    &lt;Property Name=&quot;ResourceNo&quot; Type=&quot;varchar&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;StartDate&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;EndDate&quot; Type=&quot;datetime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;HoursPerDay&quot; Type=&quot;decimal&quot; Nullable=&quot;false&quot; Precision=&quot;38&quot; Scale=&quot;20&quot; /&gt;
                &lt;/EntityType&gt;
                &lt;Association Name=&quot;FK_ResourceAssignment_JobWBS&quot;&gt;
                    &lt;End Role=&quot;JobWBS&quot; Type=&quot;MyModelNamespace.Store.JobWBS&quot; Multiplicity=&quot;1&quot; /&gt;
                    &lt;End Role=&quot;ResourceAssignment&quot; Type=&quot;MyModelNamespace.Store.ResourceAssignment&quot; Multiplicity=&quot;*&quot; /&gt;
                    &lt;ReferentialConstraint&gt;
                        &lt;Principal Role=&quot;JobWBS&quot;&gt;
                            &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
                            &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
                        &lt;/Principal&gt;
                        &lt;Dependent Role=&quot;ResourceAssignment&quot;&gt;
                            &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
                            &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
                        &lt;/Dependent&gt;
                    &lt;/ReferentialConstraint&gt;
                &lt;/Association&gt;
            &lt;/Schema&gt;
        &lt;/edmx:StorageModels&gt;
        &lt;!-- CSDL content --&gt;
        &lt;edmx:ConceptualModels&gt;
            &lt;Schema Namespace=&quot;MyModelNamespace&quot; Alias=&quot;Self&quot; xmlns=&quot;http://schemas.microsoft.com/ado/2006/04/edm&quot;&gt;
                &lt;EntityContainer Name=&quot;MyEntries&quot;&gt;
                    &lt;EntitySet Name=&quot;JobWBS&quot; EntityType=&quot;MyModelNamespace.JobWBS&quot; /&gt;
                    &lt;EntitySet Name=&quot;ResourceAssignment&quot; EntityType=&quot;MyModelNamespace.ResourceAssignment&quot; /&gt;
                    &lt;AssociationSet Name=&quot;FK_ResourceAssignment_JobWBS&quot; Association=&quot;MyModelNamespace.FK_ResourceAssignment_JobWBS&quot;&gt;
                        &lt;End Role=&quot;JobWBS&quot; EntitySet=&quot;JobWBS&quot; /&gt;
                        &lt;End Role=&quot;ResourceAssignment&quot; EntitySet=&quot;ResourceAssignment&quot; /&gt;
                    &lt;/AssociationSet&gt;
                &lt;/EntityContainer&gt;
                &lt;EntityType Name=&quot;JobWBS&quot;&gt;
                    &lt;Key&gt;
                        &lt;PropertyRef Name=&quot;JobNo&quot; /&gt;
                        &lt;PropertyRef Name=&quot;JobWBSCode&quot; /&gt;
                    &lt;/Key&gt;
                    &lt;Property Name=&quot;timestamp&quot; Type=&quot;Binary&quot; Nullable=&quot;false&quot; MaxLength=&quot;8&quot; FixedLength=&quot;true&quot; /&gt;
                    &lt;Property Name=&quot;JobNo&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;JobWBSCode&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;60&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;Description&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;50&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;Level&quot; Type=&quot;Int32&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;StartDate&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;EndDate&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;Duration&quot; Type=&quot;Decimal&quot; Nullable=&quot;false&quot; Precision=&quot;38&quot; Scale=&quot;20&quot; /&gt;
                    &lt;Property Name=&quot;LastModified&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;NavigationProperty Name=&quot;ResourceAssignment&quot; Relationship=&quot;MyModelNamespace.FK_ResourceAssignment_JobWBS&quot; FromRole=&quot;JobWBS&quot; ToRole=&quot;ResourceAssignment&quot; /&gt;
                &lt;/EntityType&gt;
                &lt;EntityType Name=&quot;ResourceAssignment&quot;&gt;
                    &lt;Key&gt;
                        &lt;PropertyRef Name=&quot;AssignmentID&quot; /&gt;
                    &lt;/Key&gt;
                    &lt;Property Name=&quot;timestamp&quot; Type=&quot;Binary&quot; Nullable=&quot;false&quot; MaxLength=&quot;8&quot; FixedLength=&quot;true&quot; /&gt;
                    &lt;Property Name=&quot;AssignmentID&quot; Type=&quot;Int32&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;ResourceNo&quot; Type=&quot;String&quot; Nullable=&quot;false&quot; MaxLength=&quot;20&quot; Unicode=&quot;false&quot; FixedLength=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;StartDate&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;EndDate&quot; Type=&quot;DateTime&quot; Nullable=&quot;false&quot; /&gt;
                    &lt;Property Name=&quot;HoursPerDay&quot; Type=&quot;Decimal&quot; Nullable=&quot;false&quot; Precision=&quot;38&quot; Scale=&quot;20&quot; /&gt;
                    &lt;NavigationProperty Name=&quot;JobWBS&quot; Relationship=&quot;MyModelNamespace.FK_ResourceAssignment_JobWBS&quot; FromRole=&quot;ResourceAssignment&quot; ToRole=&quot;JobWBS&quot; /&gt;
                &lt;/EntityType&gt;
                &lt;Association Name=&quot;FK_ResourceAssignment_JobWBS&quot;&gt;
                    &lt;End Type=&quot;MyModelNamespace.JobWBS&quot; Role=&quot;JobWBS&quot; Multiplicity=&quot;1&quot; /&gt;
                    &lt;End Type=&quot;MyModelNamespace.ResourceAssignment&quot; Role=&quot;ResourceAssignment&quot; Multiplicity=&quot;*&quot; /&gt;
                &lt;/Association&gt;
            &lt;/Schema&gt;
        &lt;/edmx:ConceptualModels&gt;
        &lt;!-- C-S mapping content --&gt;
        &lt;edmx:Mappings&gt;
            &lt;Mapping Space=&quot;C-S&quot; xmlns=&quot;urn:schemas-microsoft-com:windows:storage:mapping:CS&quot;&gt;
                &lt;EntityContainerMapping StorageEntityContainer=&quot;MyModelNamespaceStoreContainer&quot; CdmEntityContainer=&quot;MyEntries&quot;&gt;
                    &lt;EntitySetMapping Name=&quot;JobWBS&quot;&gt;
                        &lt;EntityTypeMapping TypeName=&quot;IsTypeOf(MyModelNamespace.JobWBS)&quot;&gt;
                            &lt;MappingFragment StoreEntitySet=&quot;JobWBS&quot;&gt;
                                &lt;ScalarProperty Name=&quot;timestamp&quot; ColumnName=&quot;timestamp&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;JobNo&quot; ColumnName=&quot;JobNo&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;JobWBSCode&quot; ColumnName=&quot;JobWBSCode&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;Description&quot; ColumnName=&quot;Description&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;Level&quot; ColumnName=&quot;Level&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;StartDate&quot; ColumnName=&quot;StartDate&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;EndDate&quot; ColumnName=&quot;EndDate&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;Duration&quot; ColumnName=&quot;Duration&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;LastModified&quot; ColumnName=&quot;LastModified&quot; /&gt;
                            &lt;/MappingFragment&gt;
                        &lt;/EntityTypeMapping&gt;
                    &lt;/EntitySetMapping&gt;
                    &lt;EntitySetMapping Name=&quot;ResourceAssignment&quot;&gt;
                        &lt;EntityTypeMapping TypeName=&quot;IsTypeOf(MyModelNamespace.ResourceAssignment)&quot;&gt;
                            &lt;MappingFragment StoreEntitySet=&quot;ResourceAssignment&quot;&gt;
                                &lt;ScalarProperty Name=&quot;timestamp&quot; ColumnName=&quot;timestamp&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;AssignmentID&quot; ColumnName=&quot;AssignmentID&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;ResourceNo&quot; ColumnName=&quot;ResourceNo&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;StartDate&quot; ColumnName=&quot;StartDate&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;EndDate&quot; ColumnName=&quot;EndDate&quot; /&gt;
                                &lt;ScalarProperty Name=&quot;HoursPerDay&quot; ColumnName=&quot;HoursPerDay&quot; /&gt;
                            &lt;/MappingFragment&gt;
                        &lt;/EntityTypeMapping&gt;
                    &lt;/EntitySetMapping&gt;
                    &lt;AssociationSetMapping Name=&quot;FK_ResourceAssignment_JobWBS&quot; TypeName=&quot;MyModelNamespace.FK_ResourceAssignment_JobWBS&quot; StoreEntitySet=&quot;ResourceAssignment&quot;&gt;
                        &lt;EndProperty Name=&quot;ResourceAssignment&quot;&gt;
                            &lt;ScalarProperty Name=&quot;AssignmentID&quot; ColumnName=&quot;AssignmentID&quot; /&gt;
                        &lt;/EndProperty&gt;
                        &lt;EndProperty Name=&quot;JobWBS&quot;&gt;
                            &lt;ScalarProperty Name=&quot;JobWBSCode&quot; ColumnName=&quot;JobWBSCode&quot; /&gt;
                            &lt;ScalarProperty Name=&quot;JobNo&quot; ColumnName=&quot;JobNo&quot; /&gt;
                        &lt;/EndProperty&gt;
                    &lt;/AssociationSetMapping&gt;
                &lt;/EntityContainerMapping&gt;
            &lt;/Mapping&gt;
        &lt;/edmx:Mappings&gt;
    &lt;/edmx:Runtime&gt;
    &lt;!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) --&gt;
    &lt;edmx:Designer xmlns=&quot;http://schemas.microsoft.com/ado/2007/06/edmx&quot;&gt;
        &lt;edmx:Connection&gt;
            &lt;DesignerInfoPropertySet&gt;
                &lt;DesignerProperty Name=&quot;MetadataArtifactProcessing&quot; Value=&quot;EmbedInOutputAssembly&quot; /&gt;
            &lt;/DesignerInfoPropertySet&gt;
        &lt;/edmx:Connection&gt;
        &lt;edmx:Options&gt;
            &lt;DesignerInfoPropertySet&gt;
                &lt;DesignerProperty Name=&quot;ValidateOnBuild&quot; Value=&quot;true&quot; /&gt;
            &lt;/DesignerInfoPropertySet&gt;
        &lt;/edmx:Options&gt;
        &lt;!-- Diagram content (shape and connector positions) --&gt;
        &lt;edmx:Diagrams&gt;
            &lt;Diagram Name=&quot;MyDataModel&quot;&gt;
                &lt;EntityTypeShape EntityType=&quot;MyModelNamespace.JobWBS&quot; Width=&quot;1.5&quot; PointX=&quot;0.75&quot; PointY=&quot;0.75&quot; Height=&quot;2.41404296875&quot; IsExpanded=&quot;true&quot; /&gt;
                &lt;EntityTypeShape EntityType=&quot;MyModelNamespace.ResourceAssignment&quot; Width=&quot;1.5&quot; PointX=&quot;3.875&quot; PointY=&quot;0.75&quot; Height=&quot;2.085348307291667&quot; IsExpanded=&quot;true&quot; /&gt;
                &lt;AssociationConnector Association=&quot;MyModelNamespace.FK_ResourceAssignment_JobWBS&quot;&gt;
                    &lt;ConnectorPoint PointX=&quot;2.25&quot; PointY=&quot;1.7926741536458335&quot; /&gt;
                    &lt;ConnectorPoint PointX=&quot;3.875&quot; PointY=&quot;1.7926741536458335&quot; /&gt;
                &lt;/AssociationConnector&gt;
            &lt;/Diagram&gt;
        &lt;/edmx:Diagrams&gt;
    &lt;/edmx:Designer&gt;
&lt;/edmx:Edmx&gt;
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/600/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=600&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/08/12/entity-framework-creating-a-model-using-views-instead-of-tables/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/db-model.jpg" medium="image">
			<media:title type="html">db-model</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/generated-model.jpg" medium="image">
			<media:title type="html">generated-model</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/open-with-xml-editor.jpg" medium="image">
			<media:title type="html">open-with-xml-editor</media:title>
		</media:content>
	</item>
		<item>
		<title>RIA Services: How dates are handled and sent across the wire</title>
		<link>http://smehrozalam.wordpress.com/2009/08/07/ria-services-how-dates-are-handled-and-sent-across-the-wire/</link>
		<comments>http://smehrozalam.wordpress.com/2009/08/07/ria-services-how-dates-are-handled-and-sent-across-the-wire/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 11:31:23 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[RIA Services]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[local]]></category>
		<category><![CDATA[ria service]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[timezone]]></category>
		<category><![CDATA[unspecified]]></category>
		<category><![CDATA[utc]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=589</guid>
		<description><![CDATA[The current(July) preview of RIA Services handles DateTime objects in an strange manner. Many of silverlight developers have complained in Silverlight forums that their dates are messed up. In this post, I am listing down several observations as a reference. Note that my current settings are +6 GMT.

From 	DateTime.Kind 	 DateTime.Value     [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=589&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The current(July) preview of RIA Services handles DateTime objects in an strange manner. Many of silverlight developers have complained in Silverlight forums that their dates are messed up. In this post, I am listing down several observations as a reference. Note that my current settings are +6 GMT.</p>
<pre class="brush: xml;">
From 	DateTime.Kind 	 DateTime.Value        To     DateTime.Kind  DateTime.Value
---- 	-------------   ----------------       --     -------------  ---------------
Client 	Unspecified     2009-01-01 00:00     Server 	Utc         2008-12-31 18:00
Server 	Unspecified     2009-01-01 00:00     Client 	Utc         2008-12-31 18:00
Client 	Local 	        2009-01-01 00:00     Server 	Utc         2008-12-31 18:00
Server 	Local 	        2009-01-01 00:00     Client 	Utc         2008-12-31 18:00
Client 	Utc 	        2009-01-01 00:00     Server 	Utc         2009-01-01 00:00
Server 	Utc 	        2009-01-01 00:00     Client 	Utc         2009-01-01 00:00
</pre>
<p>We can see that whatever Datetime we send, RIA service converts it to UTC when received at the other end. This could be bearable up to some extent but the worst thing is that RIA domain service treats <strong>Unspecified</strong> dates as <strong>Local </strong>and performs respective time zone conversion. Also, there is a <code>UsesUtcDateTimes</code> overridable in DomainService class but currently it does not seem to produce any effect.</p>
<p>Notice that there is no such conversion when using a WCF service, so whatever datetime value and kind we send from one side is exactlyreceived the same at the other side.</p>
<p>Lets hope the issues are fixed in the next version of RIA services.</p>
<p>My sample application that I used to test the behavior of RIA Domain Service and WCF Service can be downloaded from <a href="http://smehrozalam.files.wordpress.com/2009/08/riadatetestapplication-zip.doc">here</a>. Remember to rename it to .zip for extraction.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/589/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=589&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/08/07/ria-services-how-dates-are-handled-and-sent-across-the-wire/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>
	</item>
		<item>
		<title>Entity Framework: TimeStamp fields not recognized for optimistic concurrency model</title>
		<link>http://smehrozalam.wordpress.com/2009/08/05/entity-framework-timestamp-fields-not-recognized-for-optimistic-concurrency-model/</link>
		<comments>http://smehrozalam.wordpress.com/2009/08/05/entity-framework-timestamp-fields-not-recognized-for-optimistic-concurrency-model/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 10:53:51 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[optimistic concurrency]]></category>
		<category><![CDATA[timestamp]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=582</guid>
		<description><![CDATA[Today, while working with Entity Framework, I noticed through SQL Profiler that my update queries were not using timestamp field. I looked into my model and found that my timestamp fields have Concurrency Mode property set to None. It was quite strange; The entity model was auto generated and I wonder why the EF designer [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=582&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Today, while working with Entity Framework, I noticed through SQL Profiler that my update queries were not using timestamp field. I looked into my model and found that my timestamp fields have <code>Concurrency Mode</code> property set to <code>None</code>. It was quite strange; The entity model was auto generated and I wonder why the EF designer could not identify my timestamp field (I remember Linq To SQL designer automatically took care of such fields). Anyway, I changed <strong>Concurrency Mode</strong> to <strong>Fixed</strong> and it worked great. So, as a final note, when generating entity model from database, don’t forget to set appropriate concurrency modes for your timestamp fields as it is not done by the designer itself.</p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/timestamp.jpg"><img src="http://smehrozalam.files.wordpress.com/2009/08/timestamp.jpg?w=263&#038;h=229" alt="setting concurrency mode for timestamp field" title="setting concurrency mode for timestamp field" width="263" height="229" class="alignnone size-full wp-image-585" /></a></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/582/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=582&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/08/05/entity-framework-timestamp-fields-not-recognized-for-optimistic-concurrency-model/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/timestamp.jpg" medium="image">
			<media:title type="html">setting concurrency mode for timestamp field</media:title>
		</media:content>
	</item>
		<item>
		<title>TSQL Challenge 11: Calculating the lowest price of an item by applying discount coupons</title>
		<link>http://smehrozalam.wordpress.com/2009/08/04/tsql-challenge-11-calculating-the-lowest-price-of-an-item-by-applying-discount-coupons/</link>
		<comments>http://smehrozalam.wordpress.com/2009/08/04/tsql-challenge-11-calculating-the-lowest-price-of-an-item-by-applying-discount-coupons/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 15:54:57 +0000</pubDate>
		<dc:creator>Syed Mehroz Alam</dc:creator>
				<category><![CDATA[T-SQL]]></category>
		<category><![CDATA[challenges]]></category>
		<category><![CDATA[combinations]]></category>
		<category><![CDATA[cte]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[tsql challenge]]></category>

		<guid isPermaLink="false">http://smehrozalam.wordpress.com/?p=554</guid>
		<description><![CDATA[TSQL Challenge 11 was a practical problem. Given a a list of products and a list of discount coupons, we needed to find the minimum price for all the products based on certain rules. Here are those rules:

Maximum two coupons can be applied on the same product
The discount price can not be less than 70% [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=554&subd=smehrozalam&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://beyondrelational.com/blogs/tc/archive/2009/07/15/tsql-challenge-11.aspx">TSQL Challenge 11</a> was a practical problem. Given a a list of products and a list of discount coupons, we needed to find the minimum price for all the products based on certain rules. Here are those rules:</p>
<ul>
<li>Maximum two coupons can be applied on the same product</li>
<li>The discount price can not be less than 70% of the original price</li>
<li>The total amount of the discount can not exceed 30$</li>
</ul>
<p>Also, note that coupons are applied in a cumulative way. So the second coupon is applied on the result of the original price + first coupon.</p>
<p><strong>Sample Data:</strong><br />
Here is some sample products data:</p>
<pre class="brush: xml;">
ID NAME    PRICE
-- ------- ---------
1  PROD 1  100,00
2  PROD 2  220,00
3  PROD 3  15,00
4  PROD 4  70,00
5  PROD 5  150,00
</pre>
<p>Here are the coupons to be applied</p>
<pre class="brush: xml;">
ID NAME         VALUE  IS_PERCENT
-- -----------  ------ ----------
1  CP 1 : -15$  15     0
2  CP 2 : -5$   5      0
3  CP 3 : -10%  10     1
4  CP 4 : -12$  12     0
</pre>
<p>And here&#8217;s the required output:</p>
<pre class="brush: xml;">
ID NAME    PRICE    DISC_PRICE  TOT_DISC  RATE    COUPON_NAMES
2.-- ------  -------- ----------- --------- ------- -------------------------
3.1  PROD 1  100.00$  73.00$      27.00$    27.00%  CP 4 : -12$ + CP 1 : -15$
4.2  PROD 2  220.00$  193.00$     27.00$    12.27%  CP 4 : -12$ + CP 1 : -15$
5.3  PROD 3  15.00$   13.50$      1.50$     10.00%  CP 3 : -10%
6.4  PROD 4  70.00$   49.50$      20.50$    29.28%  CP 1 : -15$ + CP 3 : -10%
7.5  PROD 5  150.00$  120.00$     30.00$    20.00%  CP 3 : -10% + CP 1 : -15$
</pre>
<p><strong>Solution</strong></p>
<p>Interesting enough&#8230; So lets attempt to find a solution. <span id="more-554"></span>Here&#8217;s an script to populate the above sample data:</p>
<pre class="brush: sql;">
DECLARE @T TABLE (ID INT IDENTITY, NAME NVARCHAR(20),PRICE MONEY)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 1',100)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 2',220)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 3',15)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 4',70)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 5',150)

DECLARE @C TABLE (ID INT IDENTITY, NAME NVARCHAR(20), VALUE INT, IS_PERCENT BIT)
INSERT INTO @C (NAME,VALUE,IS_PERCENT) VALUES ('CP 1 : -15$',15,0)
INSERT INTO @C (NAME,VALUE,IS_PERCENT) VALUES ('CP 2 : -5$',5,0)
INSERT INTO @C (NAME,VALUE,IS_PERCENT) VALUES ('CP 3 : -10%',10,1)
INSERT INTO @C (NAME,VALUE,IS_PERCENT) VALUES ('CP 4 : -12$',12,0)
</pre>
<p>Here&#8217;s a simple approach to address the problem.</p>
<ul>
<li>We will start with the products table</li>
<li>have a cross join to apply all the coupons and get a result</li>
<li>have a cross join of this intermediate result with all the coupons (except the one that has already been applied in the previous join)</li>
<li>pick up the mininum prices</li>
</ul>
<p>Lets start coding the above approach with a series of CTEs:</p>
<p><strong>Step 1:</strong> Products with no coupons applied (We may need to start with the base products table because there can exist some products for which no discount can be applied).</p>
<pre class="brush: sql;">
--some products can not have any discount at all
;With NoDiscount As
(
	Select P.ID, P.NAME, P.PRICE, P.PRICE as DiscPrice, 0 as TotDisc, 0/P.PRICE as Rate,
		'' as Coupons, 0 as CouponsApplied, '' as CouponIDsApplied
	From @T P
)
</pre>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/nodiscount.jpg"><img class="alignnone size-medium wp-image-562" title="Products with no discount applied" src="http://smehrozalam.files.wordpress.com/2009/08/nodiscount.jpg?w=400&#038;h=82" alt="Products with no discount applied" width="400" height="82" /></a></p>
<p><strong>Step 2:</strong> Apply all coupons on the result of Step 1 using a cross Join and filter rows to meet the business rules (described in the beginning of the post). Notice that we have populated a CouponIDsApplied column that contains the IDs of all the coupons applied on a particular row. This column will help us ensuring we don&#8217;t apply the same coupon twice.</p>
<pre class="brush: sql;">
--product prices with one coupon applied
,OneCoupon As
(
	Select * from NoDiscount

	union all

	Select P.ID, P.NAME, P.PRICE, P.DiscPrice,
		P.Price - P.DiscPrice as TotDisc,
		(P.PRICE - P.DiscPrice)/P.PRICE * 100 as Rate,
		P.Coupons,
		P.CouponsApplied,
		P.CouponIDsApplied
	From
	(
		--derived table gives us better readability, otherwise the query would be filled up with lot of &quot;case when&quot; clauses
		Select P.ID, P.NAME, P.PRICE,
			Case
				When C.IS_PERCENT=0 Then P.DiscPrice-C.VALUE
				Else P.DiscPrice-(P.DiscPrice/100*C.VALUE)
			END as DiscPrice,
			Cast(P.Coupons + Case when P.Coupons&lt;&gt;N'' Then N' + ' Else N'' END + C.NAME as nvarchar(MAX)) as Coupons,
			P.CouponsApplied+1 as CouponsApplied,
			P.CouponIDsApplied + '(' + Cast(C.ID as varchar) + ')' as CouponIDsApplied

		From NoDiscount P
		inner join @C C on CHARINDEX('(' + Cast(C.ID as varchar) +  ')', P.CouponIDsApplied) = 0
	) P
	Where
		--the total amount of the discount can not exceed 30$.
		P.Price - P.DiscPrice &lt;= 30
		--the discount price can not be less than 70% of the original price (i.e. the discount itself cant be greater than 30%)
		and (P.PRICE-P.DiscPrice)/P.PRICE * 100 &lt;= 30
)
</pre>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/onecoupon.jpg"><img class="alignnone size-medium wp-image-563" title="Products with one coupon applied" src="http://smehrozalam.files.wordpress.com/2009/08/onecoupon.jpg?w=400&#038;h=290" alt="Products with one coupon applied" width="400" height="290" /></a></p>
<p><strong>Step 3:</strong> Apply all coupons on the those rows of Step 2 that have one coupon applied (The result of Step 1 will also contain rows from the base product table with no discount applied and so we do not want to re-apply coupons on them).</p>
<pre class="brush: sql;">
--product prices with two coupons applied
,TwoCoupon As
(
	Select * from OneCoupon

	union all

	Select P.ID, P.NAME, P.PRICE, P.DiscPrice,
		P.Price - P.DiscPrice as TotDisc,
		(P.PRICE-P.DiscPrice)/P.PRICE * 100 as Rate,
		P.Coupons,
		P.CouponsApplied,
		P.CouponIDsApplied
	From
	(
		Select P.ID, P.NAME, P.PRICE,
			Case
				When C.IS_PERCENT=0 Then P.DiscPrice-C.VALUE
				Else P.DiscPrice-(P.DiscPrice/100*C.VALUE)
			END as DiscPrice,
			Cast(P.Coupons + Case when P.Coupons&lt;&gt;N'' Then N' + ' Else N'' END + C.NAME as nvarchar(MAX)) as Coupons,
			P.CouponsApplied+1 as CouponsApplied,
			P.CouponIDsApplied + '(' + Cast(C.ID as varchar) + ')' as CouponIDsApplied

		From OneCoupon P
		inner join @C C on CHARINDEX('(' + Cast(C.ID as varchar) +  ')', P.CouponIDsApplied) = 0
		--only apply second coupon on rows with 1 coupon applied
		where P.CouponsApplied=1
	) P
	Where
		--the total amount of the discount can not exceed 30$.
		P.Price - P.DiscPrice &lt;= 30
		--the discount price can not be less than 70% of the original price (i.e. the discount itself cant be greater than 30%)
		and (P.PRICE-P.DiscPrice)/P.PRICE * 100 &lt;= 30

)
</pre>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/twocoupons.jpg"><img class="alignnone size-medium wp-image-566" title="Products with two coupons applied" src="http://smehrozalam.files.wordpress.com/2009/08/twocoupons.jpg?w=400&#038;h=114" alt="Products with two coupons applied" width="400" height="114" /></a></p>
<p><strong>Step 4:</strong> Apply row number to sort the resulting prices. Notice that this is the point where we can define the criteria which rows to pick when multiple combinations yield same output, e.g. pick the rows that have higher order coupon applied first (CP4 then CP1 is preferred over CP1 then CP4), or pick the rows with lowest number of coupons applied first.</p>
<pre class="brush: sql;">
,SortedPrices As
(
	Select *, ROW_NUMBER() over (partition by ID order by DiscPrice,CouponsApplied,CouponIDsApplied desc ) as rowNumber
	From TwoCoupon
)
</pre>
<p>This is the output of the above step for product 2. Notice that there are 3 combinations that give us the least price. We are about to pickup the combination with highest order coupon applied first, i.e. CP4 then CP1.</p>
<p><a href="../files/2009/08/sortedresult.jpg"><img title="Sorted result for product 2" src="../files/2009/08/sortedresult.jpg?w=300" alt="Sorted result for product 2" width="400" height="137" /></a></p>
<p><strong>Step 5:</strong> Pick up the minimum prices and format according to desired output.</p>
<pre class="brush: sql;">
Select ID, NAME, Cast(PRICE as varchar) + '$' as PRICE,
	Cast(DiscPrice as varchar) + '$' as DISC_PRICE, Cast(TotDisc as varchar) + '$' as TOT_DISC,
	Cast(Rate as varchar) + '%' as RATE, Coupons as COUPON_NAMES
from SortedPrices
Where rowNumber=1
</pre>
<p>Thats all. Here&#8217;s the final result that complies with the expected output of the challenge.</p>
<p><a href="http://smehrozalam.files.wordpress.com/2009/08/result.jpg"><img class="alignnone size-medium wp-image-564" title="Result" src="http://smehrozalam.files.wordpress.com/2009/08/result.jpg?w=400&#038;h=92" alt="Result" width="400" height="92" /></a></p>
<p>Notice that we are applying the same operation in steps 2 and 3. This makes a perfect scenario to use recursive CTEs, so lets build one. The base case (anchor) would be to select all rows from the product table and then apply coupons on each iteration. Here&#8217;s the same approach using a recursive CTE.</p>
<pre class="brush: sql;">
;With ProductDiscounts AS
(
	--some products can not have any discount at all
	Select P.ID, P.NAME, P.PRICE, P.PRICE as DiscPrice,P.PRICE*0 as TotDisc, 0/P.PRICE as Rate,
			Cast(N'' as nvarchar(MAX)) as Coupons, 0 as CouponsApplied, Cast('' as varchar(MAX)) as CouponIDsApplied
	From @T P

	union all

	--recursively apply discount coupons until maximum (in this case 2) reached
	Select P.ID, P.NAME, P.PRICE, P.DiscPrice,
		P.Price - P.DiscPrice as TotDisc,
		(P.PRICE-P.DiscPrice)/P.PRICE * 100 as Rate,
		P.Coupons,
		P.CouponsApplied,
		P.CouponIDsApplied
	From
	(
		--derived table gives us better readability, otherwise the query would be filled up with lot of &quot;case when&quot; clauses
		Select P.ID, P.NAME, P.PRICE,
			Case
				When C.IS_PERCENT=0 Then P.DiscPrice-C.VALUE
				Else P.DiscPrice-(P.DiscPrice/100*C.VALUE)
			END as DiscPrice,
			Cast(P.Coupons + Case when P.Coupons&lt;&gt;N'' Then N' + ' Else N'' END + C.NAME as nvarchar(MAX)) as Coupons,
			P.CouponsApplied+1 as CouponsApplied,
			P.CouponIDsApplied + '(' + Cast(C.ID as varchar) + ')' as CouponIDsApplied
		From ProductDiscounts P
		inner join @C C on CHARINDEX('(' + Cast(C.ID as varchar) +  ')', P.CouponIDsApplied) = 0
		--maximum 2 coupons can be applied
		where P.CouponsApplied&lt;2
	) P

	Where
		--the total amount of the discount can not exceed 30$.
		P.Price - P.DiscPrice &lt;= 30
		--the discount price can not be less than 70% of the original price (i.e. the discount itself cant be greater than 30%)
		and (P.PRICE-P.DiscPrice)/P.PRICE * 100 &lt;= 30
)

/*
Now we need to select top rows order by discount, grouped by product so we assign a row number based on the price
Note that this is the place where we define the criteria which rows to pick when multiple combinations yield same output,
e.g. pick the rows that have higher order coupon applied first (CP4 then CP1 is preferred over CP1 then CP4),
     pick the rows with lowest number of coupons applied first
*/
,SortedPrices As
(
	Select *, ROW_NUMBER() over (partition by ID order by DiscPrice,CouponsApplied,CouponIDsApplied desc ) as rowNumber
	From ProductDiscounts
)

--Result
Select ID, NAME, Cast(PRICE as varchar) + '$' as PRICE,
	Cast(DiscPrice as varchar) + '$' as DISC_PRICE, Cast(TotDisc as varchar) + '$' as TOT_DISC,
	Cast(Rate as varchar) + '%' as RATE, Coupons as COUPON_NAMES
from SortedPrices
Where rowNumber=1
</pre>
<p><strong>Comparison of the two solutions</strong><br />
We have seen two solutions to the above problem. The first one would be efficient for large number of rows since it is an static solution. To increase the no. of coupons that can be applied, we need to add one CTE per increase in the no. of allowed coupons.<br />
The second one, on the other hand, is much scalable and flexible. To change it to three or more coupons, we just need to change the <code>where P.CouponsApplied&lt;2</code> condition inside the recursive part.</p>
<p>To play with, here is complete solution script for both the versions:</p>
<pre class="brush: sql;">
DECLARE @T TABLE (ID INT IDENTITY, NAME NVARCHAR(20),PRICE MONEY)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 1',100)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 2',220)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 3',15)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 4',70)
INSERT INTO @T (NAME,PRICE) VALUES ('PROD 5',150)

DECLARE @C TABLE (ID INT IDENTITY, NAME NVARCHAR(20), VALUE INT, IS_PERCENT BIT)
INSERT INTO @C (NAME,VALUE,IS_PERCENT) VALUES ('CP 1 : -15$',15,0)
INSERT INTO @C (NAME,VALUE,IS_PERCENT) VALUES ('CP 2 : -5$',5,0)
INSERT INTO @C (NAME,VALUE,IS_PERCENT) VALUES ('CP 3 : -10%',10,1)
INSERT INTO @C (NAME,VALUE,IS_PERCENT) VALUES ('CP 4 : -12$',12,0)

/*
Solution 1: Simple solution that gives fair speed

To increase the no. of coupons that can be applied, we need to add one CTE per increase in no. of allowed coupons.
*/

--some products can not have any discount at all
;With NoDiscount As
(
	Select P.ID, P.NAME, P.PRICE, P.PRICE as DiscPrice, 0 as TotDisc, 0/P.PRICE as Rate,
		'' as Coupons, 0 as CouponsApplied, '' as CouponIDsApplied
	From @T P
)
--product prices with one coupon applied
,OneCoupon As
(
	Select * from NoDiscount

	union all

	Select P.ID, P.NAME, P.PRICE, P.DiscPrice,
		P.Price - P.DiscPrice as TotDisc,
		(P.PRICE - P.DiscPrice)/P.PRICE * 100 as Rate,
		P.Coupons,
		P.CouponsApplied,
		P.CouponIDsApplied
	From
	(
		--derived table gives us better readability, otherwise the query would be filled up with lot of &quot;case when&quot; clauses
		Select P.ID, P.NAME, P.PRICE,
			Case
				When C.IS_PERCENT=0 Then P.DiscPrice-C.VALUE
				Else P.DiscPrice-(P.DiscPrice/100*C.VALUE)
			END as DiscPrice,
			Cast(P.Coupons + Case when P.Coupons&lt;&gt;N'' Then N' + ' Else N'' END + C.NAME as nvarchar(MAX)) as Coupons,
			P.CouponsApplied+1 as CouponsApplied,
			P.CouponIDsApplied + '(' + Cast(C.ID as varchar) + ')' as CouponIDsApplied

		From NoDiscount P
		inner join @C C on CHARINDEX('(' + Cast(C.ID as varchar) +  ')', P.CouponIDsApplied) = 0
	) P
	Where
		--the total amount of the discount can not exceed 30$.
		P.Price - P.DiscPrice &lt;= 30
		--the discount price can not be less than 70% of the original price (i.e. the discount itself cant be greater than 30%)
		and (P.PRICE-P.DiscPrice)/P.PRICE * 100 &lt;= 30
)
--product prices with two coupons applied
,TwoCoupon As
(
	Select * from OneCoupon

	union all

	Select P.ID, P.NAME, P.PRICE, P.DiscPrice,
		P.Price - P.DiscPrice as TotDisc,
		(P.PRICE-P.DiscPrice)/P.PRICE * 100 as Rate,
		P.Coupons,
		P.CouponsApplied,
		P.CouponIDsApplied
	From
	(
		Select P.ID, P.NAME, P.PRICE,
			Case
				When C.IS_PERCENT=0 Then P.DiscPrice-C.VALUE
				Else P.DiscPrice-(P.DiscPrice/100*C.VALUE)
			END as DiscPrice,
			Cast(P.Coupons + Case when P.Coupons&lt;&gt;N'' Then N' + ' Else N'' END + C.NAME as nvarchar(MAX)) as Coupons,
			P.CouponsApplied+1 as CouponsApplied,
			P.CouponIDsApplied + '(' + Cast(C.ID as varchar) + ')' as CouponIDsApplied

		From OneCoupon P
		inner join @C C on CHARINDEX('(' + Cast(C.ID as varchar) +  ')', P.CouponIDsApplied) = 0
		--only apply second coupon on rows with 1 coupon applied
		where P.CouponsApplied=1
	) P
	Where
		--the total amount of the discount can not exceed 30$.
		P.Price - P.DiscPrice &lt;= 30
		--the discount price can not be less than 70% of the original price (i.e. the discount itself cant be greater than 30%)
		and (P.PRICE-P.DiscPrice)/P.PRICE * 100 &lt;= 30

)

/*
Now we need to select top rows order by discount, grouped by product so we assign a row number based on the price
Note that this is the place where we define the criteria which rows to pick when multiple combinations yield same output,
e.g. pick the rows that have higher order coupon applied first (CP4 then CP1 is preferred over CP1 then CP4),
     pick the rows with lowest number of coupons applied first
*/
,SortedPrices As
(
	Select *, ROW_NUMBER() over (partition by ID order by DiscPrice,CouponsApplied,CouponIDsApplied desc ) as rowNumber
	From TwoCoupon
)

--Result
Select ID, NAME, Cast(PRICE as varchar) + '$' as PRICE,
	Cast(DiscPrice as varchar) + '$' as DISC_PRICE, Cast(TotDisc as varchar) + '$' as TOT_DISC,
	Cast(Rate as varchar) + '%' as RATE, Coupons as COUPON_NAMES
from SortedPrices
Where rowNumber=1

/*
Solution 2: Solution using recursive CTE
Gives us high flexibility and scalability (to change it to three or more coupons,
  we just need to change the &quot;where P.CouponsApplied&amp;lt;2&amp;quot; condition inside the recursive part)
*/

;With ProductDiscounts AS
(
	--some products can not have any discount at all
	Select P.ID, P.NAME, P.PRICE, P.PRICE as DiscPrice,P.PRICE*0 as TotDisc, 0/P.PRICE as Rate,
			Cast(N'' as nvarchar(MAX)) as Coupons, 0 as CouponsApplied, Cast('' as varchar(MAX)) as CouponIDsApplied
	From @T P

	union all

	--recursively apply discount coupons until maximum (in this case 2) reached
	Select P.ID, P.NAME, P.PRICE, P.DiscPrice,
		P.Price - P.DiscPrice as TotDisc,
		(P.PRICE-P.DiscPrice)/P.PRICE * 100 as Rate,
		P.Coupons,
		P.CouponsApplied,
		P.CouponIDsApplied
	From
	(
		--derived table gives us better readability, otherwise the query would be filled up with lot of &amp;quot;case when&amp;quot; clauses
		Select P.ID, P.NAME, P.PRICE,
			Case
				When C.IS_PERCENT=0 Then P.DiscPrice-C.VALUE
				Else P.DiscPrice-(P.DiscPrice/100*C.VALUE)
			END as DiscPrice,
			Cast(P.Coupons + Case when P.CouponsN'' Then N' + ' Else N'' END + C.NAME as nvarchar(MAX)) as Coupons,
			P.CouponsApplied+1 as CouponsApplied,
			P.CouponIDsApplied + '(' + Cast(C.ID as varchar) + ')' as CouponIDsApplied
		From ProductDiscounts P
		inner join @C C on CHARINDEX('(' + Cast(C.ID as varchar) +  ')', P.CouponIDsApplied) = 0
		--maximum 2 coupons can be applied
		where P.CouponsApplied&amp;lt;2
	) P

	Where
		--the total amount of the discount can not exceed 30$.
		P.Price - P.DiscPrice &amp;lt;= 30
		--the discount price can not be less than 70% of the original price (i.e. the discount itself cant be greater than 30%)
		and (P.PRICE-P.DiscPrice)/P.PRICE * 100 &amp;lt;= 30
)

/*
Now we need to select top rows order by discount, grouped by product so we assign a row number based on the price
Note that this is the place where we define the criteria which rows to pick when multiple combinations yield same output,
e.g. pick the rows that have higher order coupon applied first (CP4 then CP1 is preferred over CP1 then CP4),
     pick the rows with lowest number of coupons applied first
*/
,SortedPrices As
(
	Select *, ROW_NUMBER() over (partition by ID order by DiscPrice,CouponsApplied,CouponIDsApplied desc ) as rowNumber
	From ProductDiscounts
)

--Result
Select ID, NAME, Cast(PRICE as varchar) + '$' as PRICE,
	Cast(DiscPrice as varchar) + '$' as DISC_PRICE, Cast(TotDisc as varchar) + '$' as TOT_DISC,
	Cast(Rate as varchar) + '%' as RATE, Coupons as COUPON_NAMES
from SortedPrices
Where rowNumber=1
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smehrozalam.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smehrozalam.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smehrozalam.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smehrozalam.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smehrozalam.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smehrozalam.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smehrozalam.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smehrozalam.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smehrozalam.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smehrozalam.wordpress.com/554/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smehrozalam.wordpress.com&blog=4540612&post=554&subd=smehrozalam&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://smehrozalam.wordpress.com/2009/08/04/tsql-challenge-11-calculating-the-lowest-price-of-an-item-by-applying-discount-coupons/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/12d4d94c607dcfa4dfc7b8ea307b3c64?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">Mehroz</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/nodiscount.jpg?w=300" medium="image">
			<media:title type="html">Products with no discount applied</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/onecoupon.jpg?w=300" medium="image">
			<media:title type="html">Products with one coupon applied</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/twocoupons.jpg?w=300" medium="image">
			<media:title type="html">Products with two coupons applied</media:title>
		</media:content>

		<media:content url="../files/2009/08/sortedresult.jpg?w=300" medium="image">
			<media:title type="html">Sorted result for product 2</media:title>
		</media:content>

		<media:content url="http://smehrozalam.files.wordpress.com/2009/08/result.jpg?w=300" medium="image">
			<media:title type="html">Result</media:title>
		</media:content>
	</item>
	</channel>
</rss>