<?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/"
	>

<channel>
	<title>devermind.com &#187; LINQ</title>
	<atom:link href="http://devermind.com/category/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://devermind.com</link>
	<description>Adrian Grigore's software development weblog. Motto: I will not waste my time looking for a clever motto.</description>
	<lastBuildDate>Fri, 03 Sep 2010 13:25:22 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>A generic base class for LINQ to SQL Data Layers</title>
		<link>http://devermind.com/linq/a-linq-disconnected-mode-abstract-base-class/</link>
		<comments>http://devermind.com/linq/a-linq-disconnected-mode-abstract-base-class/#comments</comments>
		<pubDate>Mon, 13 Oct 2008 15:04:01 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[DAL]]></category>
		<category><![CDATA[multi-tier]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=29</guid>
		<description><![CDATA[It&#8217;s hard not to fall in love with LINQ to SQL. It provides a type safe, powerful and extremely flexible way to implement data access in .NET applications. And it looks so easy to use in those nifty Microsoft evangelist presentations!
Unfortunately, after having a closer look at LINQ, I found that using LINQ in a [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s hard not to fall in love with LINQ to SQL. It provides a type safe, powerful and extremely flexible way to implement data access in .NET applications. And it looks so easy to use in those nifty Microsoft evangelist presentations!</p>
<p>Unfortunately, after having a closer look at LINQ, I found that using LINQ in a multi-tier application can be quite a struggle. This article shows the typical pitfalls of implementing the data layer with LINQ to SQL and provides an simple, convenient and flexible way to circumvent most of them.<span id="more-29"></span></p>
<p>The generic base class for a LINQ-to-SQL Database Abstraction Layers (DAL) that comes with this article has the following features:</p>
<ul>
<li>Implements the Repository pattern, allowing you to conveniently implement CRUD (Create, Update, Delete) operations with less than ten lines of code per LINQ entity type.</li>
<li>Works seamlessly in disconnected LINQ mode</li>
<li>Supports transparent database updates of LINQ entity hierarchies in one single database roundtrip.</li>
<li>As a convenience feature, it also writes all executed SQL statements to the output console when debugging your application.</li>
</ul>
<p>I&#8217;m going to assume that you have a basic understanding of what LINQ to SQL (also known as DLINQ) does and how it is used. If you don&#8217;t, have a look at this tutorial first and come back to this page to see how to use LINQ to SQL in multi-tier applications.</p>
<p><strong>The Problem</strong></p>
<p>LINQ to SQL is incredibly easy to use if you simply hook your UI layer directly to the database with LinqToDataSource objects. But that&#8217;s not very object-oriented, and certainly not an advisable architecture unless you are coding a quick and dirty application and do not plan on extending it in the long run.</p>
<p>Instead, most developers divide their applications into several layers, for example the following:</p>
<ul>
<li>Data Access Layer</li>
<li>Business Layer</li>
<li>UI Layer</li>
</ul>
<p>This is known as a multi-tier database application design. LINQ to SQL would be used in the Data Access Layer.</p>
<p>The problem with LINQ to SQL is that – despite it&#8217;s many advantages – it&#8217;s not very simple to use when implementing the data layer.</p>
<p>Have a look at the following database schema:</p>
<p>As long as you are loading and saving LINQ entities to the same data context instance (this is known as “connected mode”), implementing your Data layer with LINQ is very straightforward.</p>
<p>For example, let&#8217;s fetch the customer entity with ID==1 from the database, change its first name to “Homer” and save it back to the database. In an multi-tier database application the code might be somewhere in the UI or business layer and look like this:</p>
<pre class="brush: csharp;">

//create a new repository instance
CustomersRepository customersRepository = new CustomersRepository();
//load a customer instance and change it's FirstName;
Customer customer = customersRepository.Load(2);
customer.FirstName = &quot;Homer&quot;;
//commmit customer to database
customersRepository.Save(customer);
</pre>
<p>The easiest way to implement the data layer Load and Save functions used above is this:</p>
<pre class="brush: csharp;">
static DataClassesDataContext context=new DataClassesDataContext();
public Customer Load(int CustomerID)
{
return context.Customers.Single(c =&gt; c.ID == CustomerID);
}
public void Save(Customer toSave)
{
context.SubmitChanges();
}
</pre>
<p>This approach is using connected LINQ mode: The data context never goes out of scope, so it can always be reused to save entities to the database which are still connected to it.</p>
<p>Granted, it is convenient and works for the isolated example above, but it has severe concurrency issues because one database context is used for all database operations:<br />
When calling Save(), SubmitChanges commits ALL changed entities, not only those related to the LINQ entity that the Save Method received in the toSave parameter.</p>
<p>But even setting this flaw aside, you can&#8217;t implement the data layer in the same manner when using LINQ in a multi-tier ASP.NET application. Here, chances are that your LINQ entity is loaded with the one page request, then updated and saved to the database with the next page request. Meanwhile, your original data context has gone out of scope, making your LINQ entity disconnected.</p>
<p>And there are also many other scenarios where you need to use disconnected LINQ mode: For example you might want to implement your Database Layer as a web service, commit previously serialized LINQ entities to your database, etc.</p>
<p>Implementing the data layer with disconnected LINQ to SQL</p>
<p>So, how do we implement a Data layer Save() method that works in disconnected LINQ mode?</p>
<p>We have to</p>
<ul>
<li>Detach the entity from the old data context</li>
<li>Create a new data context</li>
<li>Attach the entity to the new context</li>
<li>Submit changes</li>
</ul>
<p>In source code, it looks like this:</p>
<pre class="brush: csharp;">
public Customer Load(int CustomerID)
{
DataClassesDataContext context = new DataClassesDataContext();
return context.Customers.Single(c =&gt; c.ID == CustomerID);
}

public void Save(Customer toSave)
{
//the old data context is no more, we need to create a new one
DataClassesDataContext context = new DataClassesDataContext();
//serialize and deserialize the entity to detach it from the
//old data context. This is not part of .NET, I am calling
//my own code here
toSave = EntityDetacher&lt;Customer&gt;.Detach(toSave);
//is the entity new or just updated?
//ID is the customer table's identity column, so new entities should
//have an ID == 0
if (toSave.ID == 0)
{
//insert entity into Customers table
context.Customers.InsertOnSubmit(toSave);
}
else
{
//attach entity to Customers table and mark it as &quot;changed&quot;
context.Customers.Attach(toSave, true);
}
}
</pre>
<p>Now you can load and alter as many entities as you like and only commit some of them to the database. But due to using disconnected LINQ, this implementation does not account for associations between LINQ entities.</p>
<p>For example, imagine you want to do the following in your business or UI layer:</p>
<pre class="brush: csharp;">
//load currently selected customer from database
Customer customer = new CustomersRepository().Load(1);
//change the customer's first name
customer.FirstName = &quot;Homer&quot;;
//add a new bill with two billingitems to the customer
Bill newbill = new Bill
{
Date = DateTime.Now,
BillingItems =
{
new BillingItem(){ItemPrice=10, NumItems=2},
new BillingItem(){ItemPrice=15, NumItems=1}
}
};
customer.Bills.Add(newbill);
//create a new provider to simulate new ASP.NET page request
//save the customer
new CustomersRepository().Save(customer);
</pre>
<p>The disconnected mode Save() method above would commit the change to the FirstName column, but simply forget about the new bill and billing items. In order to make it work, we also need to recursively Attach or Insert all associated child entities:</p>
<pre class="brush: csharp;">

public void Save(Customer toSave)
{
//the old data context is no more, we need to create a new one
DataClassesDataContext context = new DataClassesDataContext();
//serialize and deserialize the entity to detach it from the
//old data context. This is not part of .NET, I am calling
//my own code here
toSave = EntityDetacher.Detach(toSave);
//is the entity new or just updated?
//ID is the customer table's identity column, so new entities should
//have an ID == 0
if (toSave.ID == 0)
{
//insert entity into Customers table
context.Customers.InsertOnSubmit(toSave);
}
else
{
//attach entity to Customers table and mark it as &quot;changed&quot;
context.Customers.Attach(toSave, true);
}
//attach or save all &quot;bill&quot; child entities
foreach (Bill bill in toSave.Bills)
{
if (bill.ID == 0)
{
context.Bills.InsertOnSubmit(bill);
}
else

{
context.Bills.Attach(bill, true);
}
//attach or save all &quot;BillingItem&quot; child entities
foreach (BillingItem billingitem in bill.BillingItems)
{
if (bill.ID == 0)
{
context.BillingItems.InsertOnSubmit(billingitem);
}
else
{
context.BillingItems.Attach(billingitem, true);
}
}
}
}
</pre>
<p>Not very complicated, but a lot of typing. And that&#8217;s only for a trivial database scheme and one single entity type. Imagine you were implementing the database layer for several dozen entity types with a few dozen foreign key relationships. You would have to write dozens of nested foreach loops for every single LINQ entity you need a DAL Repository class for. This is not only tedious, but also error-prone. Whenever you add a new table, you&#8217;d have to add a few dozen foreach loops to various DAL Repository classes.</p>
<p><strong>How I avoided all these problems</strong></p>
<p>After quite a bit of online research, I implemented a class called RepositoryBase that you can use to quickly implement your data layer that works fine with the examples shown above.</p>
<p>In order to use it, you must first instruct the Object Relational Mapper to generate serializable LINQ entities: Open your dbml file in Visual Studio, left-click somewhere in the white area, and set “Serialization Mode” to “Unidirectional” in the “Properties” panel:</p>
<p><a href="http://devermind.com/wp-content/uploads/2008/10/linq-dal-base-class_html_m2847c2b7.png"><img class="alignnone size-medium wp-image-40" title="linq-dal-base-class_html_m2847c2b7" src="http://devermind.com/wp-content/uploads/2008/10/linq-dal-base-class_html_m2847c2b7.png" alt="" width="254" height="300" /></a></p>
<p>Now you can derive from RepositoryBase to implement your own Repository:</p>
<pre class="brush: csharp;">public class CustomersRepository :
//derive from RepositoryBase with the entity name and
//data context as generic parameters
DeverMind.RepositoryBase
{
override protected Expression&lt;Func&lt;Customer, bool&gt;&gt; GetIDSelector(int ID)
{
//ID needs to be the entity's ID column name
return (Item) =&gt; Item.ID == ID;
}
}
public partial class Customer
{
public static RepositoryBase CreateRepository()
{
//create and return an instance of this entity type's repository
return new CustomersRepository();
}
}</pre>
<p>Do this for each of your entity types, and you have a data layer working seamlessly in disconnected mode. Your derived Repository classes automatically implement the following methods:</p>
<p><a href="http://devermind.com/wp-content/uploads/2008/10/providerbase-interface.png"><img class="alignnone size-medium wp-image-41" title="providerbase-interface" src="http://devermind.com/wp-content/uploads/2008/10/providerbase-interface.png" alt="" width="178" height="300" /></a></p>
<p>As a small bonus, you can also see the SQL commands that were run against the database by ProviderBase in your debug output console when debugging your application. Thanks to Kris Vandermotten for the handy DebuggerWriter component, which is used by RepositoryBase for the SQL debug output!</p>
<p><strong>There&#8217;s no free lunch&#8230;</strong></p>
<p>There is no significant performance penalty for the Load operations, but there is a bit of reflection going on behind the scenes when you are calling the Save or Delete<br />
methods.</p>
<p>For the vast majority of your DAL needs, this probably has no significant impact on your application either. However, if you are performing a lot of update / insert / delete operations, especially with lots of nested child entities involved, then you might want to hand-code your own Save / Delete functions for the Repository classes of those child applications as described above. All Save / Delete functions are virtual, so you can easily override them.</p>
<p>Also, please note that RepositoryBase does not support recursive save or delete operations with circular dependencies.</p>
<p><strong>Conclusion</strong></p>
<p>This article and the included source code provide a simple, convenient and extensible way to implement your multi-tier LINQ data layer CRUD methods. It works in disconnected mode and supports saving and loading of nested child entities. There is a small performance penalty on Save and Load operations, but you can override those for those Repositories where Save or Load performance is critical.</p>
<p>For everything else, you&#8217;re good to go with just a few lines of code.</p>
<p><strong>Source Code</strong></p>
<p>The updated source code for this article can be found <a href="http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers">here</a>.</p>
<p><strong>Feedback Wanted!</strong></p>
<p>Thanks for your interest in this article. If you have any hints, questions or suggestions, please let me know. I&#8217;m using this class on a daily basis and am therefore always interested on how to improve it even further.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2flinq%2fa-linq-disconnected-mode-abstract-base-class"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2flinq%2fa-linq-disconnected-mode-abstract-base-class" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<a rev="vote-for" href="http://dotnetshoutout.com/A-generic-base-class-for-ASPNET-Webforms-LINQ-to-SQL-Data-Layers-devermindcom"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdevermind.com%2Flinq%2Fa-linq-disconnected-mode-abstract-base-class" style="border:0px"/></a></p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/a-linq-disconnected-mode-abstract-base-class/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #1: Using Custom ViewModels with POST action methods</title>
		<link>http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/</link>
		<comments>http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/#comments</comments>
		<pubDate>Sat, 18 Apr 2009 11:44:27 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[viewmodel]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=102</guid>
		<description><![CDATA[One of the top good practices for ASP.NET MVC is not to use the ViewData Dictionary, but to put your data in a strongly typed ViewModel instead. Many people seem to be using Linq to SQL entities as a ViewModel, because it&#8217;s a very comfortable approach. But what do you do if your view should [...]]]></description>
			<content:encoded><![CDATA[<p>One of the top good practices for ASP.NET MVC is not to use the ViewData Dictionary, but to put your data in a strongly typed ViewModel instead. Many people seem to be using Linq to SQL entities as a ViewModel, because it&#8217;s a very comfortable approach. But what do you do if your view should contain data that is not included in any of your linq entities? <a href="http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx">Scott Gu&#8217;s chapter 1 preview of his upcoming ASP.NET MVC book</a> recommends using a custom-shaped ViewModel for those cases.<span id="more-102"></span></p>
<p>One thing that still puzzled me after reading and trying to follow the chapter was how to create complex custom ViewModels (as opposed to putting all data in the ViewData dictionary or using vanilla Linq to SQL entities). Scott mentions on page 107 of the book  that you &#8220;might have the action method update a ViewModel object with the form-posted data, and then use the ViewModel instance to map or retrieve an actual domain model object&#8221;, but there is no actual example of how this would look in source code.</p>
<p>For example, let&#8217;s assume you have an edit action method with the following view:</p>
<p><a href="http://devermind.com/wp-content/uploads/2009/04/form1.png"><img class="alignnone size-full wp-image-103" title="EditForm" src="http://devermind.com/wp-content/uploads/2009/04/form1.png" alt="EditForm" width="274" height="334" /></a></p>
<p>So your edit form displays data coming from a Linq entity representing a customer (FirstName, LastName, Email, Country, AccountType), but you also need SelectLists to populate the Country and AccountType DropDownLists.</p>
<p><strong>The simple, but untyped approach: the ViewData dictionary</strong></p>
<p>The simplest approach is to use the Customer Linq entity as ViewModel and to put the two SelectLists in the ViewData dictionary. This works fine, but I dislike the fact that there is no type-safety for the two SelectLists. Instead you have to use a type cast from object to SelectList:</p>
<pre class="brush: xml;">
&lt;label for=&quot;CountryCode&quot;&gt;Country&lt;/label&gt;&lt;br /&gt;
&lt;%= Html.DropDownList(&quot;CountryCode&quot;,ViewData[&quot;Countries&quot;] as SelectList)%&gt;

&lt;%= Html.ValidationMessage(&quot;CountryCode&quot;, &quot;*&quot;)%&gt;
</pre>
<p><strong>The fully typed approach: Custom ViewModels</strong></p>
<p>So you want fully typed model data, but the linq entity does not hold all the data you need to render the view. Since you don&#8217;t want to clutter my Customer Linq to SQL entity with two properties that return the two SelectLists, the only alternative to get a fully typed view is to use a custom ViewModel:</p>
<pre class="brush: csharp;">public class CustomersFormViewModel
{
public SelectList AccountTypes { get; set; }
public SelectList Countries { get; set; }
public Customer Customer { get; set; }
}</pre>
<p>Note that the ViewModel is not a mere Linq entity anymore. Instead, it contains the one Customer Linq entity instance, plus the two SelectLists for my DropDownLists.</p>
<p>Now you can implement your view without using any typecasts:</p>
<pre class="brush: html;">

&lt;p&gt;

&lt;label for=&quot;Customer.FirstName&quot;&gt;

FirstName:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;Customer.FirstName&quot;)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.FirstName&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.LastName&quot;&gt;

LastName:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;Customer.LastName&quot;)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.LastName&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.Email&quot;&gt;

Email:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;Customer.Email&quot;)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.Email&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.CountryCode&quot;&gt;

Country&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.DropDownList(&quot;Customer.CountryCode&quot;,Model.Countries)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.CountryCode&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.AccountType&quot;&gt;

AccountType:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.DropDownList(&quot;Customer.AccountType&quot;,Model.AccountTypes)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.AccountType&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;</pre>
<p>I was wondering if the MVC framework can automatically map the form values and reconstruct a CustomersFormViewModel. In other words, can I simply implement a strongly typed POST edit action method and receive a fully populated ViewModel as a parameter like this:</p>
<pre class="brush: csharp;">
//POST: /CustomersController/Edit

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(CustomersFormViewModel model)
{
//validate data, save customer, handle validation errors...
}</pre>
<p>The answer is yes! The MVC framework even maps object hierarchies of any depth as ViewModels.</p>
<p><strong>How not to do it</strong></p>
<p>This is all really easy, but still there were few things that threw me off at the beginning.</p>
<p>The ViewModelBinder only maps properties, not public fields. A ViewModel like this cannot be mapped:</p>
<pre class="brush: csharp;">public class CustomersFormViewModel
{
public electList AccountTypes;
public SelectList Countries;
public Customer Customer;
}</pre>
<p>The names of your POSTed form values must match the object hiearchy you want them to be mapped to. Something like this will not work:</p>
<p style="margin: 0in; font-family: Calibri; font-size: 11pt;">
<pre class="brush: xhtml;">&lt;p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;

&lt;label for=&quot;FirstName&quot;&gt;

FirstName:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;FirstName&quot;,Model,Customer,FirstName)%&gt;

&lt;%= Html.ValidationMessage(&quot;FirstName&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;</pre>
<p>In hindsight both restrictions are perfectly logic and reasonable, but it&#8217;s easy enough to do it wrong nevertheless and also quite difficult to figure out what went wrong if binding does not work. Hopefully this article will help you avoid any problems with using Custom ViewModels with POST action methods.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-using-custom-viewmodels-with-post-action-methods"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-using-custom-viewmodels-with-post-action-methods" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods"><br />
<img style="border:0px" src="http://dotnetshoutout.com/image.axd?url=http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods" alt="Shout it" /><br />
</a></div>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Linq entity Version property in databound controls</title>
		<link>http://devermind.com/linq/linq-entity-version-property-in-databound-controls/</link>
		<comments>http://devermind.com/linq/linq-entity-version-property-in-databound-controls/#comments</comments>
		<pubDate>Fri, 03 Oct 2008 14:39:50 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=24</guid>
		<description><![CDATA[Since I am currently working on a multi-tier ASP.NET application, I frequently have to display Linq entities in data-driven controls such as GridView, DetailView, etc.
Most of my Linq entities have a version attribute to speed up database operations, and sometimes the entities are not only displayed, but also updated and saved back to the database. [...]]]></description>
			<content:encoded><![CDATA[<p>Since I am currently working on a multi-tier ASP.NET application, I frequently have to display Linq entities in data-driven controls such as GridView, DetailView, etc.</p>
<p>Most of my Linq entities have a version attribute to speed up database operations, and sometimes the entities are not only displayed, but also updated and saved back to the database. The first time I tried this, I got the following exception:</p>
<p><strong>A first chance exception of type &#8216;System.Data.Linq.ChangeConflictException&#8217; occurred in System.Data.Linq.dll<br />
</strong></p>
<p>The reason for this is that I was not displaying the version anywhere in the Detailsview. When saving the entity back to the database, the ObjectDataSource created a new entity with default values for all properties that were not bound to any datafields in the DetailsView. So, the entity was re-instantiated with Version==null and when trying to update the database table for the Linq entity, Linq was looking for a row with a 0 version column.</p>
<p>I thought I might work around this by simply version property of the Linq entity to an invisible Column in the Detailsview. But that only gave me a new exception when trying to update the entity:</p>
<p><strong>Sytem. InvalidOperationException: Cannot convert value of parameter &#8216;Version&#8217; from &#8216;System.String&#8217; to &#8216;System.Data.Linq.Binary&#8217;</strong></p>
<p>The reason for this is that the Version attribute in Linq entities is of the type System.Data.Linq.Binary, which can be converted to a string, but not back from string to System.Data.Linq.Binary.</p>
<p>It took me quite a while to find at least some workaround for this problem. A working &#8211; but somewhat awkward &#8211; solution is to create a VersionString propery in each entity:</p>
<pre class="brush: csharp;">
public partial class Customer
{
public string VersionString
{
get { return _Version.TimestampToString(); }
set { _Version = value.StringToTimestamp(); }
}
}

public static class DateTimeExtensions
{
public static string TimestampToString(this Binary binary)
{
return Convert.ToBase64String(binary.ToArray());
}
public static Binary StringToTimestamp(this string s)
{
return new Binary(Convert.FromBase64String(s));
}
}
</pre>
<p>Then I bound the VersionString to a hidden field in the DetailsView and the problem was gone. But this solution is not ideal since it requires the VersionString property to be defined for every single Linq entity type that uses a timestamp.</p>
<p><strong>But wait, there&#8217;s a much easier way</strong>, I stumbled across this solution while playing around with Detailsview a few days ago: Simply add the Version propery to the DataKeyNames property of the DetailsGrid. For example, if your DataKeyNames propery is usually DataKeyNames=&#8221;ID&#8221;, write DataKeyNames=&#8221;ID,Version&#8221; instead.</p>
<p>This way the DetailsView serializes the Version property to it&#8217;s view state and deserializes it again when the entity has to be recreated. No need to fiddle with the VersionString approach above.</p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/linq-entity-version-property-in-databound-controls/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Updated: Generic base class for LINQ2SQL data layers</title>
		<link>http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers/</link>
		<comments>http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 14:23:32 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[DAL]]></category>
		<category><![CDATA[multi-tier]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=79</guid>
		<description><![CDATA[Hi,
It&#8217;s been a while since I posted the first version of my generic base class for LINQ2SQL data layers. The idea behind this class was to provide a quick and simple way to implement a repository with LINQ2SQL and therefore also a solid foundation for implementing your n-tier architecture data layer. If you missed the [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>It&#8217;s been a while since I posted the first version of my generic base class for LINQ2SQL data layers. The idea behind this class was to provide a quick and simple way to implement a repository with LINQ2SQL and therefore also a solid foundation for implementing your n-tier architecture data layer. If you missed the article, you can read more about the base class <a href="http://devermind.com/linq/a-linq-disconnected-mode-abstract-base-class">here</a>.</p>
<p>The version I previously posted has worked fine for me, but it was still lacking a way to retrieve the ID and version attributes of saved entities. Due to a typo, it also did not work with entities that have more than one unique identity column. Thanks to Mike and Fabrizio for pointing out these limitations!</p>
<p>Version 0.2 available here fixes both of these issues:</p>
<p><a href="http://devermind.com/wp-content/uploads/2009/02/repositorybase_demo_02.zip">Download RepositoryBase Demo Website</a></p>
<p><a href="http://devermind.com/wp-content/uploads/2009/02/repositorybase_source_02.zip">Download RepositoryBase Source Code Only</a></p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
	</channel>
</rss>
