Pattern name for projecting DAL specific classes (such as LINQ to SQL classes) to POCO's - linq-to-sql

I was studying the Oxite project on Codeplex. It has repository interfaces, and an implementation using LINQ to SQL. The LINQ to SQL results are projected to POCO objects in the repository implementations. It looks something like:
public IQueryable<Post> GetPosts()
{
return projectPosts(excludeNotYetPublished(getPostsQuery(siteID)));
}
This is an interesting pattern, so I wondered if it has a specific name.
Thanks!

Data Mapper. See it mentioned here http://www.martinfowler.com/eaaCatalog/repository.html
"In such systems it can be worthwhile to build another layer of abstraction over the mapping layer where query construction code is concentrated".
Note that there are different views on this. I would say those that subscribe to doing that, claim the linq2sql classes are specific to the data access technology, so I guess they see it as an implementation detail of the repository.
Perhaps you mean to ask for a name on the "repository" that returns an IQueryable. I don't think there is a commonly agreed name for that one. Rob Connery used this one on his asp.net mvc storefront series: http://blog.wekeroad.com/mvc-storefront. If you look at the old blog posts on it, you can see calling a repository is actually controversial.

I think this is more of the Data Transfer Object (DTO) pattern, where results are turned into a DTO for transfer across layers. See Data Transfer Object.

Related

Question about Domain Objects, A Service Layer, and Using Linq2SQL and ASP.net MVC with the Repository Pattern

First off, apologies for the long description of my brainspace below. I'm still wrapping my head around lots of these new ideas, so I'm sure I'm describing something incorrectly. Please feel free to correct me where I'm wrong.
We are in the R&D phase of a new ASP.net MVC2 site and want to ensure that we can 1) decouple our data store from our application, 2) allow for our application to be tested via unit tests and 3) allow us to change out our datastore or use something other than Linq2SQL down the line.
This seemingly simple goal has opened up a whole new world to me that includes the Repository pattern, IoC, DI, and all sorts of other things that are making my head swim. Here's what is so far coming into focus, or at least what I believe is a somewhat correct plan to reach our goals:
We will have a number of ISpecificRepository interfaces that define the contract between users of the interface and the underlying data store.
The SpecificRepository implementations will query specific datastores and return POCO representing our domain objects (or collections of them).
Our Service Layer will perform the application specific business logic using an instance of ISpecificRepository passed to the various service methods and pass these POCO domain objects back to our presentation layer.
As mentioned, we are planning on using Linq2SQL to implement our specific repositories for the application and have decided to decouple our service layer from this implementation by creating the POCO for our domain objects and create a mapping to and from these objects to the LINQ generated entities. In the service layer, we can then create business logic to query the repository, add data, and do whatever else we need to do for each use case. This seems fine but my concern is that since we're using Linq2SQL, our specific Linq repository implementation will now have to house all of the many Get queries that the service layer requires to implement the business logic efficiently.
I'm curious as to whether this somehow breaks the Repository pattern since we're now housing application specific logic not in the service layer but in the repository instead.
The reason I feel that we need to do it this way is so that I can write more efficient Linq queries on my specific Linq repository using various DataLoadOptions, etc. without returning IQueryable from my repository up to my service layer, where it would seem that sort of logic actually belongs. Also, all of the example IRepository interfaces I've seen seem very lightweight and only provide a few methods to GetByID, GetAll, Find, Insert, Delete, and SubmitChanges to the underlying data store. In my case, it sounds like my specific repositories will be doing a great deal more than that.
Thanks for reading this far. Any and all help that can clarify my misconceptions would be greatly appreciated.
-Mustafa
our specific Linq repository
implementation will now have to house
all of the many Get queries that the
service layer requires to implement
the business logic efficiently.
I'm curious as to whether this somehow
breaks the Repository pattern
Not at all. A Repository is a collection of domain entities. If I have a Repository of Accounts, it is perfectly reasonable to want Accounts.ThatAreOverdue().
I personally prefer fluent naming. Accounts.ThatAreOverdue() feels better than AccountRepository.GetOverdue() .. but I suppose that is a point of preference.
Also, all of the example IRepository
interfaces I've seen seem very
lightweight and only provide a few
methods to GetByID, GetAll, Find,
Insert, Delete, and SubmitChanges to
the underlying data store.
A Repository interface can be thin. Find is meant to be used with the Specification pattern. Encapsulate the criteria in another object. The implementation of the criteria can be passed Linq2Sql objects from which to query - but it will be more difficult to re-use the criteria classes against in-memory domain objects (versus in database, where Linq2Sql is involved).
Our Service Layer will perform the
application specific business logic
using an instance of
ISpecificRepository passed to the
various service methods and pass these
POCO domain objects back to our
presentation layer.
Are you saying that your logic will all be in Services and the "domain objects" will be bags of properties and bound to in the view?
I don't think I'd recommend that.
If the same object that is used in the application logic is also used in the view, then you have tightly coupled the two application layers and experience says that causes problems. It will be very difficult to maintain coherence in the Services and Domain through changes if the View uses the same objects. The View will need pieces of data and they will inevitably get stuck onto places they don't really belong in the domain.

Specification Pattern defined in Domain

Using Linq to SQL, and a DDD style Domain Layer with de-coupled repositories, does anyone have any good ideas on how to implement a specification pattern without bleeding L2S concerns up into the domain layer, that is still understandable? :)
We have complex business logic surrounding the selection of a set of transaction data, and would like those rules/specifications to be owned by the Domain. We've also done a good job of keeping our domain persistence ignorant.
This presents a problem, because in order to implement a Specification, the domain (as far as I can tell) needs to see the types being queried (L2S types).
Any ideas?
Also, nHibernate is out of the question for reasons I don't want to explain.. :)
Have you considered mapping your generic Specifications into an Expression tree that would translate into proper L2S syntax? It seems that is the main problem you are hitting here. The Specification pattern isn't the problem, but the mapping to L2S is.
Linq-To-Sql classes can be partial. This means that you can extend them by implementing a partial that implements a common interface. That Interface can be shared between layers without the "bleeding" problem you are describing. The rest is just the details of your "IsStatisfiedBy" which should be easy to encapsulate.
I recently had the same issue. Different pattern, but still LINQ to SQL (L2S). I tried two different ways to avoid the leakage.
First we tried using DTOs and a mapping layer. So we wrote super simple objects that had a one to one mapping to the tables. They were all decorated with L2S attributes. We then wrote a mapping layer to map the DTOs to our business objects. All of this was hidden via the Repository pattern from Doman Driven Design. So consumers of the business objects had no idea the L2S was under the hood.
Next, mostly for variety. We tried using the XML mapping features of L2S so the objects themselves needed no attributes. For collections we exposed IEnumerable instead of any of L2S collections. If you looked at the internals of the business classes you could still detect some usage of L2S (EntitySet or Ref). But consumers of the class had no idea. So some bits of leakage but nothing drastic.
In the end we stuck with the first pattern. The second worked and we could have replaced L2S without changing the interface of the business layer, but I was never happy with XML mapping. The first pattern had a much cleaner separation between the database and the business objects. It took more code. The first one also worked better for us because it allowed us to evolve the business objects differently than the tables. In the early days of the project the xml mapping worked because our objects were pretty much one to one with the tables.
So in the end we put a layer between L2S and the domain. It worked. It took more code, but it was really simple stuff. And it was all very testable.
If you want to avoid referencing Linq2Sql from your domain layer, you must work against interfaces that represent your entities instead of working with the actual entities themselves. You then need a mapping layer between your interfaces and your entities.
I've worked this way and found it to be a severe hindrance. I switched to NHibernate for new projects and for the older projects I simply stopped worrying about the domain referencing Linq2Sql entities directly. Overcoming that restriction is simply too much of a time-cost in my opinion.

Data Repository - business objects?

I'm reading the book "ASP.NET 3.5 Social Networking - Andrew Siemer" and I got confused when he uses Repositories to access the data.
Here is the idea of his code:
public interface IAccountRepository
{
Account GetAcountByID(int acId);
void SaveAccount(Account account);
List<Account> GetAllAccounts();
}
public class AccountRepositoryLINQ : IAccountRepository
{
Account GetAcountByID(int acId){
..... LINQ query .....
...... return.....
}
void SaveAccount(Account account){
..... LINQ .....
}
List<Account> GetAllAccounts(){
..... LINQ query .....
...... return.....
}
}
The class "Account" is the one generated automatically on the "LINQ to SQL Classes".
Some of the problems I see:
1º
I code my business layer, GUI, etc... and later in time the table Accounts in the database is changed (example: change the name of one column), then I need to rebuild the "LINQ to SQL Classes" and all my code layers will need to be recoded because my "Account" object changed.
2º
If I need to have other repositories (MySQL, Oracle, XML, other), what "Account" class will I use?
What to do?
Shouldn't I use a custom Account class? This will be used in all application layers.
How do the mapping from LINQ to my custom Account class?
Using simple "myClass.Name = linqClass.Name;" ???
Isn't this consuming machine resources if I need to "map" all the classes?
There isn't a easiest/lightest way to do it?
Is this the correct approach? Is there other ways?
Good instinct..
My suggestion is to abstract away the LinqToSQL objects, and create a set of Business Domain Objects. Then the Repository can query for the needed data and map them to the Domain objects that your application uses, and return those. Now your Data Access layer is decoupled from your application, and you can now do all of the things you listed.
The mapping can be a pain, so look at tools like Automapper to accomplish this.
I have a love hate relationship with LINQ to SQL classes myself, but I thought I'd play devils advocate :-), firstly addressing the points you made:-
1º I code my business layer, GUI,
etc... and later in time the table
Accounts in the database is changed
(example: change the name of one
column), then I need to rebuild the
"LINQ to SQL Classes" and all my code
layers will need to be recoded because
my "Account" object changed.
The general approach is that you'd add behaviour to the partial classes generated by LINQ to SQL, these files won't be replaced when you refresh a table from the data context. If you change the name of the column and don't want to change the rest of your code just update the class in the designer to use the old column name?
Even if you used POCOs for persistence with NHibernate for instance you'd still need to change the mapping so I don't really see this as an issue.
2º If I need to have other repositories (MySQL, Oracle, XML, other),
what "Account" class will I use?
Personally I'd call YAGNI on this one, if you really anticipate needing support for multiple databases LINQ to SQL might not be the best solution to start with in any case (simply to keep your infrastructure consistent across the application), tools like NHibernate would have far better support for such situations.
Moving on to adding a custom account class, mapping code can be taken care of by tools like AutoMapper, though this might mean you give up things like lazy loading (which may or may not be a big deal to you).
In the end it can be quite empowering to have full control over your entities (e.g. not having to use a parameterless constructor, control over instatiation etc, simple user types that map to one or two columns) and if you feel that your application might benefit from this it's probably the way to go, but you will pay the price in the repository implementation which will be complicated by mapping code and handling whether things need to be updated / deleted / inserted.
A good middle ground might be to simply code to an interface (e.g. IAccount) this should define the properties and method you expect from an account. Your repository would then become
IAccount GetById(int accountId);
You'll then give yourself freedom over what the implementation is (i.e. whether it's implemented by a LINQ to SQL class or a projection / mapping) and if you do opt for a custom class in future it'd be a simple case of moving the implementation to that class and altering the repository implementation.
In the end it's down to the application, if you think it's going to end up a huge application with extremely complex business logic by all means I would opt for a segregated domain layer that at least tries to be persistence ignorant. If, however, it isn't and opting for the repository pattern is simply a means to achieve good testability and a simple abstraction above your data access. I don't see why explicitly referencing LINQ to SQL classes and using them as a simple domain layer is such a big deal.
I personally use a combination of NHibernate and FluentNHibernate and seperate my domain(business objects) from all other things. I use messages from my other layers, like a GUI, to my domain which has a handler which injects repositories inside that hydrate the object(s) in question and perform the business logic, the interfaces in the repositories above are a nice way to decouple if you want to use other implementations of repositories or data access.

whats the recommended Data access layer design pattern if i will apply ado entity frame work later?

I am creating a website and using Linq to SQl as a data access layer, and i am willing to make the website can work on both linq to sql and ado entity framework, without changing many things in the other layers: business logic layer or UI layer,
Whats the recommended pattern to achieve this goal? can you explain in brief how to do that?
UPDATE
As answered below that repository pattern will help me a lot,
i checked nerd dinner website and understood it, but i found this code inside:
public class DinnersController : Controller {
IDinnerRepository dinnerRepository;
//
// Dependency Injection enabled constructors
public DinnersController()
: this(new DinnerRepository()) {
}
public DinnersController(IDinnerRepository repository) {
dinnerRepository = repository;
}
Which means as i understood that it declare a dinnerRepository using the interface IDinnerRepository , and in the constructor gave it the DinnerRepository, which will be in my case for example the linq to sql implementation,
My question is if i need to switch to ado.net entity framework, i will need to edit this constructor line or there is a better solution for this?
Update 2
Where should i put this Respository Interface and the classes which implement it in my solution, in the data access layer or in the business layer?
The Repository pattern is a good choice. If you implement it as an interface; then you can change out the concrete classes and not have to change anything else.
The Nerd Dinner walkthrough has an excellent example of the Repository pattern (with interface).
The code you listed there would go in your controller (if you were doing an MVC Application); and you create any class you wanted so long as it implemented the IDinnerRepository interface (or you could have something like an IRepository interface if you wanted to design an interface that everyone had to implement that did the basic CRUD actions, and then implement specific interfaces if you needed more (but let's not go interface crazy).
If you're 'tiering' your application, then that part would go in the "Business Logic" layer, and the Repository would be in the "Data Access Layer". That constructor contract would be the 'loosely' coupled part.
I wound up using a minor variation on the "Repository" pattern. I picked it up from the excellent Nerd Dinner tutorial. You can find the whole tutorial here and the code is on Codeplex.
Don't let all the MVC put you off if your not in an MVC situation, the underlying encapsulation of Linq2SQL is a good one. In a recent update of a codebase I went from Linq2SQL to Linkq2EF and all the changes were nicely dealt with in the repository, no outside code had to be touched.
It is also worth noting that the RIA Services stuff comes with a similar pattern. You point it at Linq2Sql or Linq2EF and it build you a basic layer over it complete with CRUD. That layer is in source code so you could just rip it out and use it in a non RIA project but I just leave it as is and link to it in other projects so I use the layer even if I ignore the over-the-wire abilities.

Repository, Entity objects and Domain Objects

In my Repositories, I am making assignments to my domain objects from the Linq Entity queries. I then have a service layer to act on these object returned from repositories.
Should my Domain objects be in the repository like this? Or should my repositories be restricted to the Entities and Data Access, and instead have my service layer make assignments to the domain objects?
Doing all assignments in Repository seems easier, but now the distinction between my database and domain objects is not apparent. What is proper practice here? tia
IMO if the app is relativly simple and you cant imagine ripping out the Data access go ahead and make the asignments in the Repository. But if you think the app will get more complicated in the future or that you may want to change the data access keep this functionality out of the repositories.
I have done apps with assignement in the repositories and other in the service layer and yet another one i had a seperate conversion layer (it was not a one on one conversion and the objects were complex).
One thing to remember about best practices, There there to help, if it makes thing more dificult then dont use it.
I used to not like it. But now usually never look back. Basically the thing is that if you need to change to an external datasource that is structured different, you can set up a new mapping along with the implementation of the repository code and be done with it.
It is about data mapping. Check this link: http://www.martinfowler.com/eaaCatalog/repository.html
Also check this related question: IRepository confusion on objects returned. I have used a similar mapper, but have made it operated at the IQueryable level, which have made able to do some pretty interesting stuff while working with the Domain Object after the mapping.