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.