Apply interfaces in C # to link to database

0

I have this big problem and it's that besides being new to programming, it's quite difficult. The subject is the following, I need to apply MVP to a small desktop program that I am developing and for this I need to completely unlink the view layer with the creation of objects. For example, in the following code I have the creation of the db and I have to make an equality, how do I apply interfaces? Thank you very much!

private void btnGuardar_Click(object sender, EventArgs e)
    {
        using (DataContext db = new DataContext())
        {
            Paciente obj = pacienteBindingSource.Current as Paciente;
            if (obj != null)
            {
                if (db.Entry<Paciente>(obj).State==System.Data.Entity.EntityState.Detached)
                {
                    db.Set<Paciente>().Attach(obj);
                }
                if (obj.PacienteID == 0)
                {
                    db.Entry<Paciente>(obj).State = System.Data.Entity.EntityState.Added;
                }
                else                   
                    db.Entry<Paciente>(obj).State = System.Data.Entity.EntityState.Modified;

                db.SaveChanges();
                gridPacientes.Refresh();
                pControls.Enabled = false;
            }
        }
    }
    
asked by ginona 10.02.2018 в 22:08
source

2 answers

0

The model view controller, allows you to reuse code, in this case it helps you not to have to write the code to connect to the database in each new class that you need.

Example:
Class Connection

using MySql.Data.MySqlClient;

public class Connect {

public string usuario = "root";

private string a = "0000";

private int aux;

public MySqlConnection conexion = new MySqlConnection();

public void Asignar(string c) {
    contrase;
    a = c;
}

public void conectar() {
    conexion = new MySqlConnection();
    try {
        conexion.ConnectionString = ("server=localhost;user=" 
                    + (usuario + (";password=" + contrase)));
        (a + ";database=hotel;port=3306");
        conexion.Open();
        // '   MsgBox("Conectado")
        aux = 1;
    }
    catch (Exception ex) {
        MsgBox(ex.Message);
    }

}

public void Cerrar() {
    try {
        conexion.Close();
        MsgBox("sesion cerrada");
        aux = 0;
    }
    catch (Exception ex) {
        MsgBox(ex.Message);
    }

}

}

When you need to open the connection to the database you can call them using inheritance or declaring the object inside the class.

Heritage:

  

Class Registration: Connect {   }
  connect ()

answered by 12.02.2018 в 02:25
0

Watch this tutorial in case it is helpful for you to MVP

    
answered by 12.02.2018 в 12:53