You could have a repository:
public interface IUsersRepository
{
public User GetUser(int id);
}
then implement it:
public class UsersRepository: IUsersRepository
{
private readonly string _connectionString;
public UsersRepository(string connectionString)
{
_connectionString = connectionString;
}
public User GetUser(int id)
{
// Here you are free to do whatever data access code you like
// You can invoke direct SQL queries, stored procedures, whatever
using (var conn = new SqlConnection(_connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id, name FROM users WHERE id = @id";
cmd.Parameters.AddWithValue("@id", id);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
return null;
}
return new User
{
Id = reader.GetInt32(reader.GetOrdinal("id")),
Name = reader.GetString(reader.GetOrdinal("name")),
}
}
}
}
}
and then your controller could use this repository:
public class UsersController: Controller
{
private readonly IUsersRepository _repository;
public UsersController(IUsersRepository repository)
{
_repository = repository;
}
public ActionResult Index(int id)
{
var model = _repository.GetUser(id);
return View(model);
}
}
This way the controller is no longer depend on the implementation of your data access layer: whether you are using plain ADO.NET, NHibernate, EF, some other ORM, calling an external web service, XML, you name it.
Now all that's left is to configure your favorite DI framework to inject the proper implementation of the repository into the controller. If tomorrow you decide to change your data access technology, no problem, simply write a different implementation of the IUsersRepository
interface and reconfigure your DI framework to use it. No need to touch your controller logic.
Your MVC application is no longer tied to the way data is stored. This makes it also easier to unit test your controllers in isolation as they are no longer tightly coupled to a particular data source.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…