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.
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.
– João Borba
You can pass the direct company object on the contact that Entity will insert, then you do not need to query.
– Bruno Costa
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
– Bruno Costa