DataProvider vs Repository
First, let me add some concepts:
Repository
A Repository
is a pattern which allow you to store objects in a place, could be anything like databases, xml, txt, logs, etc. Some applications use a repository to implement the database persistence and it is used on the business logic layer of the application. Look this article to know more.
http://msdn.microsoft.com/en-us/library/ff649690.aspx
Data Provider
A DataProvider
is a set of components that provides connection with a database. Some dataProviders can implement only one database like MySql
, PostgreSql
, Oracle
(these are not supported natively by .Net), other can connect with more databases like OleDb, since the database supports it. You can see more here on this like:
http://msdn.microsoft.com/en-us/library/a6cd7c08(v=vs.110).aspx
If you want to know more, take a look at the ADO.NET
specification. There are some classes and concepts which is important to know like Connection
, Command
, Transaction
.
http://msdn.microsoft.com/en-us/library/h43ks021(v=vs.71).aspx
Difference between them
The difference between them is the a Repository
which implements a database persistence uses a Data Provider
to access a database, so, the repository encapsulates a data provider.
This is a important principle because it is nice to keep a loose coupling between the layers of your application, in other words, other layers does not want to know how it is persisted by the Repository, it just persist and retrieve when necessary.
All the database access is provided for the DataProvider
inside a Repository
.
A practical sample, could be a method of the repository:
public Person Get(int id);
{
Person p = null;
using (var con = new SqlConnection("your connection string"))
{
con.Open();
using (var command = new SqlCommand("select * from Person where id = @id", con))
{
command.Parameters.AddWithValue("@id", id);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
p = new Person();
p.Name = reader["Name"].ToString();
// other properties....
}
}
}
con.Close();
}
return p;
}
Actually, you would not need to create a PersonDataProvider
. DataProvider is ADO.NET classes which give you a database access directly, using classes that implements base interfaces from ADO.NET like IDbConnection
, IDbCommand
, IDbTransaction
, etc. Now if you want to name your data access classes with a DataProvider
sufix, no problem.
I think it is nice to have a ORM
tool like Entity Framework
or NHibernate
implementing access database inside a Repository and not ADO.NET with a DataProvider and inject some dependencies of this ORM like ISessionFactory
inside the repository's contructor.