Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could have a repository:</p> <pre><code>public interface IUsersRepository { public User GetUser(int id); } </code></pre> <p>then implement it:</p> <pre><code>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")), } } } } } </code></pre> <p>and then your controller could use this repository:</p> <pre><code>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); } } </code></pre> <p>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. </p> <p>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 <code>IUsersRepository</code> interface and reconfigure your DI framework to use it. No need to touch your controller logic.</p> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload