I have read a lot about Unit of Work and Repositories patterns.
What I have never seen is how would I retrieve data. UoW does not make sense for Select statements.
I will use asp.net MVC with n-tier architecture and this point I never see in any tutorial or article:
Where and how do I call SELECT statements, with/without INNER JOINs, using these patterns?
Calling directly DataContext from Service Layer?
Unit of Work is for updating the model. Indeed for querying you don't need it. When using the Repository Pattern everything db related (selects, joins etc) is part of the repository implementation.
The repository consumer, for example the Controller, takes a dependency on the repository interface (an abstraction) while the concrete repository is injected by the DI Container. The consumer never sees the db or things from it, it just sees the repository methods which should return objects the controller needs and understands (even if you return an ROM entity, the controller doesn't know it's an entity).
One important thing is to understand that the repository interface defines the WHAT not the HOW. The implementation deals with the "how". This means the controller doesn't build queries, the repository does. You just ask it what you want and it magically delivers.
Related
I am building ASP.NET MVC 5 application.
I read about Repository and Unit of Work (UoW) Patterns here.
These examples use Entity Framework which adds a high-level of abstraction itself.
I am using ADO.NET and not EF. I want to know:
Whether Repository and UoW patterns makes any sense with ADO.NET?
How will my Repositories and UoW look with ADO.NET? Any Samples?
Can I add a separate class library for Repository or to make it a part of DAL?
I've written a blog post which teaches you on how to write driver independent code and how to implement Uow/Repository pattern with plain ADO.NET.
It's a bit too long to include in this answer, but basically the IDbtransaction will represent your Unit oF Work (or be contained in one) and every repository will take the transaction or UoW in it's constructor.
To create a command using a IDbTransaction
using (var cmd = transaction.Connection.CreateCommand())
{
cmd.Transaction = transaction;
//do a CRUD operation here.
}
If you look at the definitions of the patterns, and the patterns required to support them, you'll see that, if you start to implement them yourself, you'll never be wandering far from creating your own ORM. While this is a fascinating task, it's never worth it when you consider NHibernate and EntityFramework.
However, to answer your question, I found Fowler's PoEAA book invaluable in learning how to write my own UoW, DataMappers and Repositories, all based on ADO.Net. It's written by someone who's obviously done it for real, made all the mistakes and then documented them so that you don't have to. I haven't read the article you've linked, however I'm often wary of using articles like this as they only demonstrate a surface-level consideration of patterns like this.
The Unit of Work pattern is more important when you're talking about standard ADO.NET because you have to make absolutely sure that the connections you're opening are only open for the required period of time, achieved by wrapping connections inside using statements.
Unit of Work in ADO.NET would look something like this:
using (SqlConnection con = new SqlConnection(//connection string)
{
using (SqlCommand cmd = new SqlCommand(storedProcname, con))
{
//...
}
}
As you're using using statements to encompass your unit of work, you can be assured that under the hood SqlConnection.Dispose() calls the SqlConnection.Close() method, and SqlCommand.Dispose() calls SqlCommand.Close().
As answered in your previous question, you can separate these two out if you wish to do so, but personally I think they should be the same thing.
Some time ago I wrote a blog post why that very tutorial you've linked is harmful . tldr; a repository uses a DAO implementing UoW, but the repository should not be part of a UoW. Unless you like to complicate your code base/life.
To answer your questions:
Once you're using EF or any other ORM, UoW is automatically implemented there. If you go the micro-ORM path (there is no valid reason to use ado.net directly) , the UoW is basically the db transaction. A repository should always deal with application objects, never with ORM (persistence) objects. If your app objects are used as persistence entities, then you probably have a standard CRUD app, and you don't really need the repository pattern. For simple apps, use the ORM directly (it saves a lot of time).
A Repository makes use of a DAO implementing UoW as an implementation detail. The rest of the app isn't aware of anything outside the repository (interface) itself.
A repository interface is defined where it's used (usually a the Domain/Business layer). The repository implementation is part of the DAL. Note that you should use repositories only for changing the model (create/update/delete). For queries, it's much easier and maintainable to have query services (objects) handling a specific use cases and which work with the db directly.
There's a a LOT of misusing the repository pattern out there, I suggest reading my "Repository for dummies" post to understand that's a very simple pattern which has nothing to do with the complicated examples you're usually seeing.
I have implemented Repository + UnitOfWork pattern in my DAL, I am using Entity Framework (EF) to connect to the DB.
The service layer calls UnitOfWork to get a specific repository, and then interacts with repository methods using EF Entities.
The returned EF Entities from Repository to Service, are then mapped into Models (POCO objects, only properties, no functionality), and then these POCOs are passed to the Controller that called the Service in the first place.
All looks good so far, except when:
I need to use "Joins" in my LINQ queries in my repository, and return a custom object to the service layer.
The problem here is, that I was making sure, my repository only takes in and sends out EF Entities. But if I need to use join, I'll be populating a custom Model object, and will then be passing back Model instead of EF Entity.
To tackle the above problem, I was thinking that I should change my repository such that, it takes IN entities (e.g. for ADD, DELETE, UPDATE), but returns back Models (for select methods etc).
This means, my service layer will be creating Entities from Models, and then passing entities to the Repository, for any ADD, UPDATE, DELETE
And my Repository will be creating Models from Entities when returning results of a select LINQ queries.
Any thoughts if I'll be in a greater problem later if I choose to go with the above design?
If the above design is not a good solution, any other advise?
You're using the wrong repository approach, the anti-pattern. The Repository makes sens only as a decoupling pattern i.e you want tot decouple the Business Layer(BL) from the Persistence Layer(PL).
This means, your Bl (and services) don't know about EF or any other ORM. This means that your repository interface only know about what BL knows,that is the business objects. Your repository should NEVER expose EF, IQueryable or other PL detail.
First of all you need UoW pattern ONLY when updating a model, never just for queries. Then, when you're asking the repository for something, you tell it what you want and the repository will use EF, create queries, joins etc and maps the query results to the POCO the repository returns . So the mapping from EF entities to domain objects is done inside the repository.
Actually, ALL work related to the database via EF (or any other ORM) is done inside the repository. The BL just gets their object in the final form. That's the whole point of the repository.
What you're doing now is wrong, because you are doing repository's work at the BL level, violating the Separation of Concerns principle. The proper use of repository is like I wrote above.
P.S: In case you wonder, the generic repository is an anti pattern, stay away from it. As a side note, a generic repository interface is not the same thing as a generic repository.
I am about to implement the unit of work pattern with MVC3.
I have:
MVC Service Layer (BLL)
Repository Layer
Multiple types of databases
I want my service layer to get the IUnitOfWork passed to it by my IOC container. (This is easy and not part of this question).
So my service layer will do this: (Note: this is pseudo code)
(using unitOfWork)
{
ProductSqlRepository.Update();
PersonOracleRepository.Update();
IUnitOfWork.Commit();
}
All the samples I can find use EF. Whilst one of my repositories might use EF others may not.
My question is then, can I use the Unit of work pattern across multiple repositories that may sit above different types of databases (ie... EF, Oracle... other)
So, if I want to wrap an update to a SQL database and an oracle database in the ONE unit of work call, is the unit of work the way to do it.
As I mentioned, all examples I can find are for 100% EF solution, I need to mix and match.
Thanks
RuSs
The UnitOfWork scope is essentially already defined in MVC since all of your logic is done within an action. The common pattern I've seen (and what I ended up doing in my app) is to handle your unit of work via an attribute you register globally to your app and handle setting up whatever unit of work logic (transactions etc) you need to in the OnActionExecuting and OnActionExecuted of that attribute. There are a few caveats like making sure that the action isn't a child action and checking for ModelState errors but there are examples of this online. Also note that if you do not use viewmodels exclusively in your views, you may run into issues with certain frameworks lazy loading data in a view after your unit of work scope has closed.
My project used nHibernate and I used these two posts as inspiration for my implementation. Hopefully they'll give you a few ideas as well.
http://ayende.com/blog/4809/refactoring-toward-frictionless-odorless-code-what-about-transactions
http://slynetblog.blogspot.ca/2011/04/lightweight-nhibernate-and-aspnet-mvc.html
In my asp.net mvc 3 application, I'm using the repository pattern.
I have 3 entities, Company, Country, City. Each of them has their own repository. Company entity has FoundedCountry and FoundedCity foreign keys.
Now in a view, I want to show the company details. In this view I want to view Company details as well as, FoundedCountry name and FoundedCity name. In my opinion I have to handle this with a kind of JOIN query. But I'm stuck at how to achieve this in repository pattern. How can I handle this JOIN in repository pattern?
Thank you.
The repository should have a task-based interface. This means that ORM's, joins etc are inside the repository. The app just sees an interface whtch returns an object that it can use.
This means you don't create a repository around a table (it pretty much defeats the purpose). In your scenario I suggest you have (at least) 2 repositories: one will handle everything related to updating the model and the other will serve only reads (queries).
This means the query repository will return only the data you want (it basically returns view model bits). Of course, the actual tables and joins are an implementation detail of the repository.
Don't construct your repository pattern in a way that is preventing joins! This usually means to use the same ORM context (DataContext/ObjectContext) for all instances associated with the current HTTP request.
I consider it to be an anti-pattern to have a generic IRepository because database access is rarely constrained to a single type of entity at the same time.
You could consider the DataContext/ObjectContext to be a repository by itself.
A last advice: If you don't know what a repository abstraction is good for - don't use one.
I am confused as to the limitations of what gets defined in the Repositories and what to leave to the Services. Should the repository only create simple entities matching tables from the database or can it create complex custom object with combinations of those entities?
in other words: Should Services be making various Linq to SQL queries on the Repository? Or should all the queries be predefined in the Repository and the business logic simply decide which method to call?
You've actually raised a question here that's currently generating a lot of discussion in the developer community - see the follow-up comments to Should my repository expose IQueryable?
The repository can - and should - create complex combination objects containing multiple associated entities. In domain-driven design, these are called aggregates - collections of associated objects organized into some cohesive structure. Your code doesn't have to call GetCustomer(), GetOrdersForCustomer(), GetInvoicesForCustomer() separately - you just call myCustomerRepository.Load(customerId), and you get back a deep customer object with those properties already instantiated. I should also add that if you're returning individual objects based on specific database tables, then that's a perfectly valid approach, but it's not really a repository per sé - it's just a data-access layer.
On one hand, there is a compelling argument that Linq-to-SQL objects, with their 'smart' properties and their deferred execution (i.e. not loading Customer.Orders until you actually use it) are a completely valid implementation of the repository pattern, because you're not actually running database code, you're running LINQ statements (which are then translated into DB code by the underlying LINQ provider)
On the other hand, as Matt Briggs' post points out, L2S is fairly tightly coupled to your database structure (one class per table) and has limitations (no many-many mappings, for example) - and you may be better off using L2S for data access within your repository, but then map the L2S objects onto your own domain model objects and return those.
A repository should be the only piece of your application that knows anything about your data access technology. So it should not be returning objects generated by L2S at all, but map those properties to model objects of your own.
If you are using this sort of pattern, you may want to re think L2S. It generates up a data access layer for you, but doesn't really handle impedance mismatch, you have to do that manually. If you look at something like NHibernate, that mapping is done in a more robust fashion. L2S is more for a 2 tier application, where you want a quick and dirty DAL that you can extend on easily.
If you're using LINQ then my belief is that the repository should be a container for your LINQ syntax. This gives you a level of abstraction of the database access routines from your model object interfacing. As Dylan mentions above there are other views on the matter, some people like to return the IQueryable so they can continue to query the database at a later point after the repository. There is nothing wrong with either of these approaches, as long as you're clear in your standards for your application. There is more informaiton on the best practices I use for LINQ repositories here.