Creating a Data Access Layer with Linq to SQL, part 2

Last time, we looked at how Linq To SQL might impact how we think about what a Data Access Layer (DAL) is, based on the dependencies between assemblies. This time, we'll take a different approach: let's look at typical Linq to SQL code, and try to decide where to put it. I'll use a code sample from the "DLinq Overview for CSharp Developers" document included in the Linq May CTP (in C# 3.0, but the same applies to VB9).

A simple start

Let's take a look at the following code:

Northwind db = new Northwind(@"c:\northwind\northwnd.mdf"); 

var q = from c in db.Customers
where c.City == "London"
select c;

foreach (var cust in q)
Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);
 

It should be clear that the first line belongs in the DAL. The DataContext encapsulates a database connection, and knows about the physical location of the database. That is not something that higher layers should know about.

Let's say the actual query definition belongs in the DAL too, but clearly, the foreach loop sits in some higher layer. That means the two first statements need to be encapsulated in some function in the DAL, for example as follows (sticking with the "Entity Access Layer" terminology introduced before):

public class CustomersEal 
{
private Northwind db = new Northwind(@"c:\northwind\northwnd.mdf");
    public IQueryable<Customer> GetCustomersByCity(string city) 
{
return from c in db.Customers
where c.City == city
select c;
}
}
 

The business layer then contains the following code:

CustomersEal customersEal = new CustomersEal();
 
foreach (var cust in customersEal.GetCustomersByCity("London"))
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);
 

Looks good, doesn't it? All the business layer knows about the database, is that it can return Customer objects.

Problems

But wait, what if I write the following in my business layer:

CustomersEal customersEal = new CustomersEal();
 
var q = from c in customersEal.GetCustomersByCity("London")
        orderby c.ContactNamer
        select new { c.CustomerID, c.City };
 
foreach (var cust in q)
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);
 

This code highlights a few interesting facts.

First of all, it wasn't the DAL that executed the query, at least not in the traditional sense of the word. The DAL (CustomersEal to be precise) merely supplied the definition for the query. The query got executed when the foreach statement started looping over the result! In a traditional DAL, a call to a method like GetCustomersByCity would have executed the query, but not with Linq, at least not if we implement our code like this.

Secondly, the business layer can refine the query definition. This definitely has some advantages, but I realize some might argue that this is really bad. Note though, that the business layer cannot redefine the query, or execute just any query it wants. Or can it? You need the DataContext to start the process, and only the DAL has access to that, right? In fact, the Entity Layer generated by SQLMetal is referenced by the business layer too; it needs it to get to the definitions of the entities!

Thirdly, it is absolutely not clear where a developer should draw the line between what's business logic, and what belongs in the DAL. I could have moved the orderby into the DAL (especially if I always want customers to be ordered by their ContactName). But likewise, I could have moved the where clause to the business layer! How do I decide what to do?

I hate it when developers have to make choices like that during routine development. Choosing takes time, and that's not likely to improve productivity. But much worse is the fact that different developers will make different choices. Even a single developer may make different choices from one day to the next. That leads to inconsistencies in the code. Developers will spend more time trying to understand the code they're reading, because it doesn't always follow the same pattern. That's bad for productivity. In the worst case scenario, developers start rewriting each other's code, just so it matches their choice of the day. That kills productivity. (Wasn't Linq all about improving productivity?)

The solution?

We need a clear and simple criterion to decide which code goes where.

Note that the absolute minimum for a DAL is the following:

public class CustomersEal  
{
    private Northwind db = new Northwind(@"c:\northwind\northwnd.mdf");
 
    public IQueryable<Customer> GetCustomers()
    {
        return db.Customers;
    }
}
 

It's a bit silly of course, if that's all this layer does, we might just as well skip it (the connection string should be externalized in a configuration file anyway, and a default constructor that reads the connection string from the config file should be added to the Northwind DataContext in a partial class). Silly or not, it is a "lower bound" to an EAL as we have defined it here. I believe there's an "upper bound" too: I think the DAL shouldn't do projections (well, it definitely should not expose anonymous types). But that still leaves us with a very broad range. How to make a choice?

I'm inclined to say that the only way to make a clear and simple choice once and for all, it to go with the minimalist approach. And indeed, that means we don't need/write/use an Entity Access Layer. The business logic directly accesses the one assembly generated by SQLMetal, one assembly per database that is.

How's that for a DAL?


Comments (38) -

May 1. 2008 11:12 AM

I'm interested have you had the better understanding of creating DAL? Perhaps, you can share your thoughts on the part 3?

April 30. 2009 08:06 PM

Very interesting finding Kris.  Would you mind to share your thoughts about the line you would make between business layer and data access layer?  Thanks.

January 9. 2010 11:53 PM

no loss robot

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

no loss robot

January 15. 2010 02:53 AM

Astral Travel

Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!

Astral Travel

January 15. 2010 09:00 AM

grants payoff debts

I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

grants payoff debts

January 20. 2010 07:11 AM

billigt internet

I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.

billigt internet

January 23. 2010 09:18 PM

rosacea treatment

While this subject can be very touchy for most people, my opinion is that there has to be a middle or common ground that we all can find. I do appreciate that youve added relevant and intelligent commentary here though. Thank you!

rosacea treatment

January 28. 2010 08:31 PM

avg free download

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

avg free download

January 31. 2010 01:20 PM

wealthy Affiliate University

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

wealthy Affiliate University

February 3. 2010 03:42 PM

fast cash loans

What helps people, helps business.

fast cash loans

February 3. 2010 03:57 PM

faxless cash advance

Problems are not stop signs, they are guidelines.

faxless cash advance

February 3. 2010 09:40 PM

huggies diaper coupons

I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.

huggies diaper coupons

February 4. 2010 11:11 PM

payday loans

One man can be a crucial ingredient on a team, but one man cannot make a team.

payday loans

February 4. 2010 11:27 PM

online payday loans

You have the power to change.

online payday loans

February 8. 2010 05:02 PM

ergonomic office chairs

Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me mad so any assistance is very much appreciated.

ergonomic office chairs

February 8. 2010 09:16 PM

merchant cash advance

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

merchant cash advance

February 9. 2010 08:53 AM

teeth whitening

Fresh activity is the only means of overcoming adversity.

teeth whitening

February 9. 2010 09:18 AM

colon cleaner

To solve any problem, here are three questions to ask yourself: First, what could I do? Second, what could I read? And third, who could I ask?

colon cleaner

February 13. 2010 07:26 PM

How To Get Rid Of Eczema

You may have not intended to do so, but I think you have managed to express the state of mind that a lot of people are in. The sense of wanting to help, but not knowing how or where, is something a lot of us are going through.

How To Get Rid Of Eczema

February 14. 2010 01:51 PM

mini chihuahua

I completely agree with the above comment, the internet is with a doubt growing into the most important medium of communication across the globe and its due to sites like this that ideas are spreading so quickly.

mini chihuahua

February 18. 2010 09:04 AM

York home Builders

Great post! I am just starting out in community management/marketing media and trying to learn how to do it well - resources like this article are incredibly helpful. As our company is based in the US, it?s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine enthusiasm and share the fact that your product is useful in that case.

York home Builders

February 20. 2010 11:10 PM

perfect golf swing

I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!

perfect golf swing

February 24. 2010 03:50 AM

Internet marketing

I admit, I have not been on this webpage in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. I thank you to help making people more aware of possible issues.
Great stuff as usual...

Internet marketing

February 25. 2010 08:29 PM

electronic cigarette

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

electronic cigarette

February 25. 2010 09:46 PM

electronic cigarette

You may have not intended to do so, but I think you have managed to express the state of mind that a lot of people are in. The sense of wanting to help, but not knowing how or where, is something a lot of us are going through.

electronic cigarette

February 28. 2010 05:31 AM

Social Marketing

I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.

Social Marketing

March 4. 2010 04:01 AM

Pay Per Call

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

Pay Per Call

March 5. 2010 12:40 AM

boards

Great post! I am just starting out in community management/marketing media and trying to learn how to do it well - resources like this article are incredibly helpful. As our company is based in the US, it?s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine enthusiasm and share the fact that your product is useful in that case.

boards

March 5. 2010 12:26 PM

boards

Great post! I am just starting out in community management/marketing media and trying to learn how to do it well - resources like this article are incredibly helpful. As our company is based in the US, it?s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine enthusiasm and share the fact that your product is useful in that case.

boards

March 8. 2010 08:44 AM

tradesmart university

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

tradesmart university

March 9. 2010 10:02 AM

http://www.trafficultimatumreport.com/

While this subject can be very touchy for most people, my opinion is that there has to be a middle or common ground that we all can find. I do appreciate that youve added relevant and intelligent commentary here though. Thank you!

http://www.trafficultimatumreport.com/

March 10. 2010 01:41 AM

billig hjemmeside

Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I'm more of a visual learner,I found that to be more helpful well let me know how it turns out! I love what you guys are always up too. Such clever work and reporting! Keep up the great works guys I've added you guys to my blogroll. This is a great article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.

billig hjemmeside

March 10. 2010 09:30 AM

oregon duii

Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It's always nice when you can not only be informed, but also entertained! I'm sure you had fun writing this article.

oregon duii

March 12. 2010 01:14 PM

improve sperm taste

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four emails with the same comment.
Is there any way you can remove me from that service?
Thanks!

improve sperm taste

March 13. 2010 11:10 PM

silver braclet

I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!

silver braclet

March 16. 2010 09:51 AM

emekli sandıgı

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

emekli sandıgı

March 16. 2010 04:31 PM

arac sorgulama

I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!

arac sorgulama

March 16. 2010 04:45 PM

outdoor gazebo

I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.

outdoor gazebo

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Download the U2U brochure

Download Brochure

Receive the U2U Newsletter. Submit your email address:
 
 


 


Search

rss  RSS

Recent posts

None

Archive

Blogroll