Doubt to enter record with foreign key. ENTITY FRAMEWORK

Asked

Viewed 374 times

1

I’m a beginner (starting bemmmm) in programming, and I have a case to develop, which would be a Crud, using Asp.net (C#) and Entity Framework. I created a simple contact registration form, where there is a company name field. Table contact and table Company, where there is a link field between the two. In the register I inform the company name. How do I so that when recording this form, the record is first inserted in the company table, and then the contact one is placed in the foreign key field the company code?

I tried to do something like this, but I couldn’t solve it until now

protected void btnGravar_Click(object sender, EventArgs e)
    {
        using (ModelConexao db = new ModelConexao())
        {

            Contato contato = new Contato()
            {
                nome = txtNome.Text,
                telefone = txtTelefone.Text,
                email = txtEmail.Text,
                idEmpresa = db.Empresa
                 .Where(c => c.nome == txtEmpresa.Text)
                 .Select(c => c.codigo)
            };                          

            db.Contato.Add(contato);
            db.SaveChanges();
        }

        this.DataBind()

The idea is that when registering enter the record in the secondary table (company), and look for the code (Idempresa) of the company to save in the Contact, making the call of this field.

1 answer

1

When we use the Entity, we cannot set the field ID with the primary table value, we should use it in object form. Make a query and turn a variable into an object, and arrow its object empresa class Contato, as in the example below:

    using (ModelConexao db = new ModelConexao())
    {
     var empresa = db.Empresa.Where(c => c.nome == txtEmpresa.Text).FirstOrDefault();

        Contato contato = new Contato()
        {
            nome = txtNome.Text,
            telefone = txtTelefone.Text,
            email = txtEmail.Text,
            Empresa = empresa
        };                          

        db.Contato.Add(contato);
        db.SaveChanges();
    }

    this.DataBind()
  • In this example of yours, you’re only looking at the company table right? In my case, I want to register the company, and then with the code idEmpresa generated (automatically), I use in Contact. I don’t know if I could explain it better.

  • You can pass the direct company object on the contact that Entity will insert, then you do not need to query.

  • In addition: it is oriented to do as the example above, doing query, because Entity will create a hash pro object and will not give conflict to insert in the future. Advice: insert the company, query and search the company, and then do as the example above, insert the contact by passing the company object

Browser other questions tagged

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