Stored Procedure in Entity Framework without edmx template

Asked

Viewed 2,415 times

7

I have a project that uses the Entity Framework without a model edmx, we register the entities manually create a class and insert it into the context.

Someone uses this format and knows how to register a Stored Procedure in this way?

  • 2

    About "sign up manually", you mean Code First?

  • Extato @Guilhermejsantos... had forgotten what it called...

2 answers

8


As of version 5 of the Entity Framework there is a simple way to run an Stored Procedure on the basis of DbContext, using property DataBase, see:

using(MeuContexto context = new MeuContexto())
{
    SqlParameter param = new SqlParameter("@idCliente", 1);     
    context.Database.ExecuteSqlCommand("sp_ExcluirCliente @idCliente", param);
}

Or even run Stored Procedures with feedback, whose return may be an entity of your context:

public List<Cliente> Clientes()
{
    using(MeuContexto context = new MeuContexto())
    {
        return context.Database.SqlQuery<Cliente>("exec sp_Clientes).ToList();
    }
}

4

Complementing the above information:

To run a stored Procedure vc can do as per the code below:

using (var conn = new SqlConnection(connectionString))
{
   try
  {
      SqlCommand command = new SqlCommand("[dbo].[nome_da_procedure]", conn);
      command.CommandType = CommandType.StoredProcedure;
      command.Parameters.Add(new SqlParameter("@PROC_PARAMETRO", SqlDbType.Int)).Value = 100;
      command.Parameters.Add(new SqlParameter("@PROC_PARAMETRO1", SqlDbType.VarChar)).Value = 'valor';
      conn.Open();
      command.ExecuteNonQuery();
  }
}

Some details regarding the execution of the trial are: You can assign the result of a precedent to a variable:

var returnValue = command.ExecuteReader(); //Retorna a linha que foi executada

Taking the returned values:

string variavel = "";
while (returnValue.Read())
{
    variavel = returnValue["COLUNA_TABELA"].ToString();
}

Browser other questions tagged

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