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

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 7. 2010 12:29 PM

Bredbånd

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.

Bredbånd

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

March 18. 2010 11:28 PM

sell timeshare

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.

sell timeshare

March 31. 2010 06:53 AM

ND Payday Loans

When planning for a year, plant corn. When planning for a decade, plant trees. When planning for life, train and educate people.

ND Payday Loans

March 31. 2010 07:44 AM

AR Payday Loans

One chance is all you need.

AR Payday Loans

April 6. 2010 07:30 PM

hikaye

Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

hikaye

April 15. 2010 04:16 AM

essay writing tips

free pspGO isos coming very soon download now, very goodly site welcome to best russia site get ready to rumble at games iso

essay writing tips

April 15. 2010 11:51 AM

loans

It's well known that money makes us free. But how to act when someone has no cash? The one way is to get the loan and just small business loan.

loans

April 15. 2010 03:05 PM

kapadokya

Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post. Keep up your work.

kapadokya

April 21. 2010 09:24 PM

plaka sorgulama

Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

plaka sorgulama

April 22. 2010 05:02 PM

anime-live

gr8 Thank 4 shar Very intriguing article.

anime-live

April 23. 2010 07:39 AM

rezzan kiraz

I just couldnt leave your website before saying that I really enjoyed the quality facts you provide to all your visitors. Would be back generally to check up on new stuff in you article!

rezzan kiraz

April 23. 2010 07:55 PM

fallar fal bakma

Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

fallar fal bakma

April 26. 2010 08:53 PM

trafik ceza sorgulama

Hello,I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.

trafik ceza sorgulama

April 26. 2010 11:44 PM

plagiarism detection

Some students transpire the responsibility to expert writers because they don't have the skill to compose a good paper about this topic in that the cause why students need to use plagiarism detector, but such guys like creator don't do that. Thanks for the knowledge

plagiarism detection

April 28. 2010 08:47 AM

thy bilet fiyatları

Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information

thy bilet fiyatları

May 2. 2010 09:20 PM

online payday loans

A man is a success if he gets up in the morning and gets to bed at night, and in between he does what he wants to do.

online payday loans

May 4. 2010 02:27 AM

ringtones download

You are sharing a kind of really good thought! We think, that would be compared with original metropcs ringtones from the ringtones sites.

ringtones download

May 4. 2010 03:51 AM

papers service

It very elegant  how detailed topic on cognition topic has been well enhance here within this blog. Please keep it up. we enjoy it. I know that you are a well-recognized and trusted source  on the Internet and I will use this for my buy term paper needs. Thanks.

papers service

May 4. 2010 09:37 AM

bağkur borc sorgulama

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.

bağkur borc sorgulama

May 5. 2010 09:25 PM

sgk

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

sgk

May 14. 2010 12:55 AM

dissertation writing

Some persons do know that it is reasonable to buy the mini dissertation or buy dissertation just about this topic, than to create by personal efforts.

dissertation writing

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading