1
I need to enter values in an X table, then recover the id of it, so that I can send in the second Y table the id of X and other values, but I do not know how to do this. Follow the code below what I’m trying to do without success.
class DCadastro
{
private string _nome;
private string _displina;
public string Nome { get => _nome; set => _nome = value; }
public string Displina { get => _displina; set => _displina = value; }
public string Inserir(DCadastro dCadastro)
{
string resp = "";
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = Conexao.Cn;
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO PROFESSOR(nome) VALUES (@nome); SELECT SCOPE_IDENTIY(); INSERT INTO DISCIPLINA(disciplina, idProfessor) VALUES (@disciplina, @idProfessor);";
cmd.Parameters.AddWithValue("@nome", Nome);
Int32 idRetorno = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Parameters.AddWithValue("@disciplina", Displina);
cmd.Parameters.AddWithValue("@idProfessor", idRetorno);
resp = cmd.ExecuteNonQuery() == 1 ? "OK" : "Registro não foi inserido";
}
catch(Exception erro)
{
throw erro;
}
finally
{
if (con.State == System.Data.ConnectionState.Open) con.Close();
}
return resp;
}
Augusto, thank you so much! I did the tests now and it was all perfect!! Thank you very much!!!
– Phil