Doubt about Insert in bank with foreign key using Inline

Asked

Viewed 945 times

1

I have a question, how to insert data in a Mysql table, using English, I have the tables below:

inserir a descrição da imagem aqui

I am using the method below to insert:

public void inserirCarteira(float cpf, string codigo, double valor, int quant, double vtotal)
    {
        try
        {

            validarInserir(cpf, codigo, valor, quant, vtotal);
            // instancia  o banco de dados
            bancotccEntities1 bco = new bancotccEntities1();
            bco.Database.Connection.Open();
            // cria um objeto 
            carteira cart = new carteira();
            // popula o objeto
            cart.cpf = cpf;
            cart.codigo = codigo;
            cart.valoracao = valor;
            cart.qtdacao = quant;
            cart.vtotalacao = vtotal;

            // adciona um objeto ao banco
            bco.AddTocarteira(cart);
            //salva o objeto no banco
            bco.SaveChanges();
            bco.Database.Connection.Close(); 
        }
        catch (Exception e1)
        {

            throw new Exception(e1.Message.ToString());
        }
    }

I know I have to use my foreign key but I don’t know what it would be like: Cart.carteira ?

If that’s how I’m going to enter values since the idusuario is the primary key of the user table and is auto increment, so I do not know what will be the value of this field at the time of making an insertion.

Can someone give me an idea of how to do?

  • I don’t understand. Do you want how to fill in which foreign key to enter? Wallet or User?

  • First I suggest you standardize the table names, decide some pattern can be separated by underscore or uppercase tp v_invested or vInvestido, second Do not need to write idusuario, if it is already in the user table it is evident that the id would refer to the user. Class is better to start with capital letter, it would not be wallet and yes Wallet.

  • Okay thanks! I’ll write it down.

  • Hi Gypsy my idea was to insert data in the Wallet table.

1 answer

1

The problem is that you have placed Wallet as dependent on User and User Portfolio ie you can only enter a Wallet if there is a User linked to it and a User if there is a Wallet.

Try to fill in the key and/or relationship object between types before running Savechanges()

Your mapping this confusing way, you have the Wallet Object and user with the attributes CPF and Idcarteira, what are the attributes of relationship?

Can the User have 1 and only 1 Wallet? Can the User have 0 or N Wallets ? User may have 1 or N Portfolios ?

You need to define these points before creating the objects.

Browser other questions tagged

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