how to call stored procedure with linq

0

Good morning everyone. I have stored procedure in sql server and I would like to call it in my c# application, via linq . Thanks in advance for any help

    
asked by anonymous 16.09.2016 / 12:29

2 answers

2

Good afternoon, guys. I've solved the problem. For those who have the same doubt, there is the solution:

public List<SP_Comb> ListByCliente(int parametro1, string parametro2)
{
  List<SP_Comb> ListaCliente = new List<SP_Comb>();

  var q = DataContext.SP_ComboEntidade(parametro1, parametro2);

  foreach (var lista in q)
  {
    ListaCliente.Add(lista);
  }
  return ListaCliente;
}

where: SP_Comb - stored procedure mapping (via sqlmetal) SP_ComboEntidade - stored procedure

    
16.09.2016 / 13:37
2

Create the Stored Procedure in your database.

CREATE PROCEDURE BuscaCliente @nome varchar(255)          
AS
BEGIN
  SELECT * from Cliente where nome = @nome
END
  • In Visual Studio add a file of type LINQ to SQL, in my case I'll add it with the name Bank.dbml.

  • When creating the file, I added a new connection in Server Explorer pointing to my test database and navigate to the folder StoredProcedures

  • Click and drag the StoredProcedures into the Bank.dbml file

  • A Method will be added with the name of the SP, in the code just call the SP

The code below shows the use of the procedure:

BancoDataContext bd = new BancoDataContext();

var resultado = bd.BuscaCliente("celso");
foreach (var r in resultado){
  Console.Write(r.nome);
}
Console.ReadKey();

Source: link

    
16.09.2016 / 13:34