Doubt to insert record with foreign key. ENTITY FRAMEWORK

0

I'm a beginner (well, beginner) in programming, and I have a case to develop, which would be a Crud, using ASP.NET (C #) and Entity Framework. I've created a simple contact registration form, where there is a company name field. Contact table and Company table, where there is a connection field between the two. In the register I inform the name of the company. How do I save the company code in the foreign key field when writing this form, first enter the record in the company table, and then in the foreign key field?

I tried to do something like this, but I could not solve it so far

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 registration in the secondary table (company), and look for the company code (CompanyID) to save in the Contact, connecting this field.

    
asked by anonymous 07.04.2018 / 02:24

1 answer

0

When we use Entity , we can not set the ID field to the value of the primary table, we should use it in object form. Make a query and make a variable in object, and arrow its object empresa of 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()
    
07.04.2018 / 02:34