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

Asked

Viewed 92 times

1

I’m creating an app like a bench to train C, but I ran into a situation. I have a database with the tables Accounts, Clients and Tiposconta. In the table Tiposconta there are 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 into a combobox to select the desired type. My question is as follows, how do I make so that when I register the account the ID of the account type is assigned to the new object "account" created?

Follow the code below:

Classe Conta:

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;
    }

Class Typoconta

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


    public TipoConta()
    {
    }


}

Form Cadastrodecontas

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;


                }
  • The problem is that you are picking up an object that already exists in your database and ADD it, you have to ADD the object that you are actually inserting and attaching what already exists.

1 answer

0

Except for a lot of problems in your code...

you can remove that line:

comboTipoConta.ValueMember = "id";

and thus use the allocation:

conta.tipoConta = comboTipoConta.SelectedValue as TipoConta;

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


Other excerpts you can remove as they are doing nothing:

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

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


 if (comboTipoConta.SelectedIndex >= 0)

You do not need to check for a selected item. When Fill in 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 account type to enter. The insert of the two is exactly the same.


Ps.

Whereas there are not many options for account types, it is possible to use a enumerable for that reason:

public enum TiposConta
{
    ContaCorrente,
    ContaPoupanca,
    ContaSalario
}

Thus, there would be one less table in the database, and comparisons become simpler:

if (obj.TipoConta == TiposConta.ContaCorrente)
{
    //É uma conta Corrente
}
  • Author’s comment (no punctuation to comment, tried to edit my reply): I made the suggested modifications and he assigned the object to the new account, but is trying to add the account type as a new object, then I get a Primary Key error because the Savings and Current ID already exists in the bank. Sqlexception: Violation of PRIMARY KEY Constraint 'Pk__tmp_ms_x_3214ec07f7cb4935'. Cannot Insert Duplicate key in Object 'dbo.Tiposconta'. The Duplicate key value is (1). How to make it not try to add as new account type object?

  • As for the comments on the rest of the code, it is quite messy because I started the course in Alura using the data of the accounts saved in memory addresses, now that I am taking the course of Entity Framework, I am remodeling the code.

  • The issue of differentiation at the time of saving accounts was the following, I have a current account class and savings account that inherits from Account, in those child classes there are some methods of drawing, transfer etc with differences in fees, but as I got some errors when I tried to enter, I went back one step to try to solve this problem of attributing the type of account and then see what I could do about the accounts son. Thanks so much for the tips, they helped me a lot!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.