How to assign a database value to a new object in C #?

1

I'm creating an application like a bank to train C #, but I stumbled into a situation. I have a database with the Accounts, Clients, and Account Types tables. In the table TypeCounts there is registered the item "Savings" with ID "1" and the item "Chain" with ID "2". When I register a new account, I load the Account Types in a combobox to select the desired type. My question is the following, how do I when I register the account the account type ID is assigned to the new "account" object created?

Follow the code below:

Account Class:

public class Conta
{
    [Key]
    public int numero  { get; set; }

    public double saldo { get; protected set; }
    public TipoConta tipoConta { get; set; }
    public Cliente cliente { get;  set; }


    public Conta(Cliente idCliente)
    {
        this.cliente = idCliente;
        this.numero = numero;
        this.saldo = saldo;
        this.tipoConta = tipoConta;
    }

Account Type Class

public class TipoConta
{
    public int id { get; set; }
    public string descricao { get; set; }


    public TipoConta()
    {
    }


}

Form Account Master

public partial class CadastroDeContas : Form
{
    private CaixaEletronico aplicacaoPrincipal;   

    public CadastroDeContas(CaixaEletronico aplicacaoPrincipal)
    {
        this.aplicacaoPrincipal = aplicacaoPrincipal;
        InitializeComponent();
    }

    private void CadastroDeContas_Load(object sender, EventArgs e)
    {

        using (BancoContext contexto = new BancoContext())
        {
            comboTipoConta.DataSource = contexto.TiposConta.ToList();
            comboTipoConta.ValueMember = "id";
            comboTipoConta.DisplayMember = "descricao";
            comboTipoConta.Refresh();
            comboTipoConta.SelectedIndex = -1;

            //comboTipoConta.Items.Add("CORRENTE");
            //comboTipoConta.Items.Add("POUPANÇA");
        }
    }

    public void Limpar()
    {

        txtTitularNovaConta.Text = "";
        txtCpf.Text = "";
        comboTipoConta.Text = "";
    }


    public void btnCadastrar_Click(object sender, EventArgs e)
    {
        using (var contexto = new BancoContext())
        {
            var tiposConta = contexto.TiposConta.ToList();
        }

        if (txtTitularNovaConta.Text != "")
        {

            //converte os textos de entrada

            string nome = txtTitularNovaConta.Text;
            string cpf = txtCpf.Text;



           if (comboTipoConta.SelectedIndex >= 0)
            {
                //verifica se conta poupança ou corrente

                switch (comboTipoConta.SelectedIndex)
                {
                    case 0:

                        Cliente cliente = new Cliente();
                        Conta conta = new Conta();

                        cliente.Cpf = cpf;
                        cliente.Nome = nome;
                        conta.cliente = cliente;


                        this.aplicacaoPrincipal.AdicionaConta(cliente, conta);
                        using (var contexto = new BancoContext())
                        {
                            var tiposConta = contexto.TiposConta.ToList();
                            conta.tipoConta.id = Convert.ToInt32(comboTipoConta.ValueMember);

                            contexto.Clientes.Add(cliente);
                            contexto.Contas.Add(conta);


                            contexto.SaveChanges();
                            aplicacaoPrincipal.AdicionaConta(cliente, conta);
                        }
                        MessageBox.Show("Conta " + comboTipoConta.SelectedItem + " cadastrada com Sucesso");

                        Limpar();
                        break;

                    case 1:

                        Cliente cl = new Cliente();
                        Conta c = new Conta();

                        cl.Cpf = cpf;
                        cl.Nome = nome;
                        c.cliente = cl;
                        c.tipoConta.descricao = comboTipoConta.SelectedItem.ToString();
                        c.tipoConta.id = Convert.ToInt16(comboTipoConta.ValueMember);

                        this.aplicacaoPrincipal.AdicionaConta(cl, c);
                        using (var contexto = new BancoContext())
                        {
                            contexto.Clientes.Add(cl);
                            contexto.Contas.Add(c);
                            contexto.SaveChanges();
                            aplicacaoPrincipal.AdicionaConta(cl, c);
                        }
                        MessageBox.Show("Conta " + comboTipoConta.SelectedItem + " cadastrada com Sucesso");

                        Limpar();
                        break;


                }
    
asked by anonymous 03.03.2018 / 00:34

1 answer

0

Removing various issues you have in your code ...

You can remove this line:

comboTipoConta.ValueMember = "id";

and then use the assignment:

conta.tipoConta = comboTipoConta.SelectedValue as TipoConta;

With the ValueMember assigned ("id"), comboTipoConta.SelectedValue will return the Id of the object selected in the combo. Without the ValueMember assigned, it will return the selected object itself.

Other passages that you can remove because you are not doing anything:

    using (var contexto = new BancoContext())
    {
        var tiposConta = contexto.TiposConta.ToList();
    }
  

You do not need the list of account types at the time of writing. The whole list is already in the combo, and what you need will be the one selected.

 if (comboTipoConta.SelectedIndex >= 0)
  

You do not need to check for a selected item. When filling in the combo, the first item is selected, in which case it will never fall into a condition comboTipoConta.SelectedIndex < 0

switch (comboTipoConta.SelectedIndex)
  

You do not need to check the type of account to enter. The insert of the two is exactly the same.

Ps.

Since there are not many options for account types, you can use enumerable to do this:

public enum TiposConta
{
    ContaCorrente,
    ContaPoupanca,
    ContaSalario
}

So, I would have one less table in the database, and comparisons become simpler:

if (obj.TipoConta == TiposConta.ContaCorrente)
{
    //É uma conta Corrente
}
    
03.03.2018 / 12:50