Ver Mensaje Individual
  #1 (permalink)  
Antiguo 28/12/2016, 11:18
jm_shinigami
 
Fecha de Ingreso: marzo-2011
Ubicación: San Salvador
Mensajes: 49
Antigüedad: 13 años, 1 mes
Puntos: 0
Clase manejadora de conexion en proyecto

Buen dia.

Estoy iniciando un proyecto de ASP.NET con MVC y C#, no soy muy habilidoso con esto de C# asi que recurro a los que saben.

He buscado en internet una clase para poder controlar mi conexion a la BDD, ya tengo en mi archivo web.config las cadenas de conexion que necesitare. El inconveniente viene a raiz de optimizar recursos es decir me gustaria hacer una funcion llamada por ejemplo getConexion() y quiza pasar a getConexion un parametro que determine que base ocupare.

No he encontrado una forma de hacerlo, realize un ejemplo bastante sencillo pero no le veo utilidad ya que siempre en cada controlador estaria creando una funcion getConexion().

Aca el ejemplo:

Mi Modelo
Código ASP:
Ver original
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Configuration;
  6. using IBM.Data.Informix;
  7.  
  8. namespace Clientes.Models
  9. {
  10.     public class Home
  11.     {
  12.         private bool cnx_open;
  13.         private IfxConnection dbh;
  14.  
  15.         public string PersonID { get; set; }
  16.         public string Name { get; set; }
  17.  
  18.         public Home(string arg_id)
  19.         {
  20.             GetConnection();
  21.             PersonID = arg_id;
  22.            
  23.             try
  24.             {
  25.                 IfxCommand cmd = new IfxCommand();
  26.                 cmd.Connection = dbh;
  27.                 cmd.CommandText =string.Format("select bodega from almacen where id_bodega = '{0}'", PersonID);
  28.  
  29.                 IfxDataReader reader = cmd.ExecuteReader();
  30.  
  31.                 try
  32.                 {
  33.                     reader.Read();
  34.  
  35.                     if (reader.IsDBNull(0) == false)
  36.                         Name = reader.GetString(0)+" "+PersonID;
  37.                     else
  38.                         Name = null;
  39.  
  40.                     reader.Close();
  41.                 }
  42.                 catch (IfxException e)
  43.                 {
  44.                     string MessageString = "Read error occurred  / entry not found loading the Column details: "+ e.ErrorCode + " - " + e.Message + "; \n\nPlease Continue";
  45.                     //MessageBox.Show(MessageString, "SQL Read Error");
  46.                     reader.Close();
  47.                     Name = MessageString;
  48.                 }
  49.             }
  50.             catch (IfxException e)
  51.             {
  52.                 string MessageString = "The following error occurred loading the Column details: "+ e.ErrorCode + " - " + e.Message;
  53.                 Name = MessageString;
  54.             }
  55.  
  56.             dbh.Close();
  57.         }
  58.        
  59.         private void GetConnection()
  60.         {
  61.             cnx_open = false;
  62.  
  63.             dbh = new IfxConnection();
  64.            
  65.             dbh.ConnectionString = ConfigurationManager.ConnectionStrings["001"].ConnectionString;
  66.            
  67.             if (Open_Local_Connection())
  68.             {
  69.                 cnx_open = true;
  70.             }
  71.             else
  72.             {
  73.                 //MessageBox::Show("No database connection connection made...\n Exiting now", "Database Connection Error");
  74.                 //Application::Exit();
  75.             }
  76.  
  77.         }
  78.  
  79.         private bool Open_Local_Connection()
  80.         {
  81.             try
  82.             {
  83.                 dbh.Open();
  84.                 return true;
  85.             }
  86.             catch (Exception e)
  87.             {
  88.                 return false;
  89.             }
  90.         }
  91.     }
  92. }

Mi Controlador
Código ASP:
Ver original
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Configuration;
  7. using IBM.Data.Informix;
  8. using Clientes.Models;
  9.  
  10. namespace Clientes.Controllers
  11. {
  12.     public class HomeController : Controller
  13.     {
  14.  
  15.         Home bodega = new Home("1233");
  16.  
  17.         // GET: Home
  18.         public ActionResult Index()
  19.         {
  20.             return View(bodega);
  21.         }
  22.     }
  23. }

Y por ultimo mi vista
Código ASP:
Ver original
  1. @model Clientes.Models.Home
  2. @{
  3.     //ViewBag.Title = ".:: Titulo ::.";
  4. }
  5.  
  6. <h2>Prueba</h2>
  7. <p>Nombre: @Model.Name</p>

Como ven hay un metodo que obtiene la conexion GetConnection() este se invoca en el metodo necesario pero siempre y cuando este dentro del mismo controlador.

Lo que quiero es una solucion global para llamar solo GetConnection() .

Espera de orientacion.

Saludos.