<?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; multi-tier</title>
	<atom:link href="http://devermind.com/tag/multi-tier/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>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>
		<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>
	</channel>
</rss>
