Dr. StrangeLinq or How I Learned to Stop Worrying and Love Linq
So, I finally got around to writing this up. Should have done it a long time ago. People have been asking me for a while where LINQ goes. Does it go in the Data Access Layer or in the Business Layer or ...? My stock answer has always been: "It goes where ever you want it to go." But lately I just don't feel like that is good enough. I was recently asked this again at a user meeting and from an email sent by Bob P. from Stillwater, OK. Once and for all here is the answer that I managed to come up with:
N-Tier and Remote Applications with LINQ to SQL
http://msdn.microsoft.com/en-us/library/bb882661.aspx
LINQ to SQL N-Tier with Web Services
http://msdn.microsoft.com/en-us/library/bb882663.aspx
And finally this from Matt Warren with his post on LINQ FAQ's:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2769747&SiteID=1
===
Q: Where should I put my business logic? The system I’m currently developing uses static methods on the entities themselves for loading, saving and other operations.
A: The DataContext conforms to the Unit of Work design pattern. A work context must exist and be maintained separate from the entities themselves. You should either place all your business logic as methods on the DataContext or devise a separate business context that encapsulates a DataContext instance. You should not be using static methods.
Q: Are LINQ to SQL entities Business Entities or Data Transfer Objects? How do I build a business layer on top of LINQ to SQL?
A: LINQ to SQL entities are both business entities and data transfer objects. LINQ to SQL takes the place of your Data Access Layer and is the basis for your Business Layer. You can add business logic directly to the DataContext or encapsulate the DataContext in your own business context. The purpose for making a separate business context would be to restrict access to other DataContext methods. If this is not an issue for you, putting all business logic methods on the DataContext is the best choice.
===
For a little more detail on the "unit of work" and datacontext stuff, check out this blog post for starters:
http://www.iridescence.no/post/ASPNET-MVC-DataContext-and-The-Unit-of-Work-Pattern.aspx
And there you go, have fun! :)