C# class as parameter in SQL Server

Asked

Viewed 241 times

3

You can create a class in C# and the same class in SQL Server that represents a tabela (ID, Nome, Telefone) and create a precedent where I would pass as parameter this class .

This is the class example

puclic class Cliente
{
     public int ID;
     public string Nome, Telefone;
}

At the time of reading the database data I would call the example Process PROC_Select_Cliente and this precedent returns me an object of the client class.

At the time of the Insert I would call the Procedure PROC_Insert_Cliente passing as parameter an instance of the client class where there is all the information.

I don’t know if it exists so I don’t have a code to show.

  • Hello, welcome! Your question is a bit confusing. Is there any code you are already working on? You just want to persist an object in a database and be able to retrieve it to manipulate?

  • 1

    I recommend using the Entity Framework. Search and it is not difficult to use

1 answer

4

The easy and simple way is by using Dapper.

Running Stored Procedure for Selection

var cliente = connection.Query<Cliente>("PROC_Select_Cliente", new {ID = 1}, 
    commandType: CommandType.StoredProcedure).First();

Running Stored Procedure for Insertion

var parametros = new DynamicParameters();
parametros.Add("@ID", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
parametros.Add("@Nome", "Fulano");
parametros.Add("@Telefone", "(11) 2345-6789");

connection.Execute("PROC_Insert_Cliente", parametros, commandType: CommandType.StoredProcedure); 

int id = parametros.Get<int>("@ID");

Remembering that connection is any object that implements IDbConnection. May SqlConnection, for example.

Now, pass an object to a function that executes a Stored Procedure is a step a little further. I don’t know if it’s worth detailing in this answer.

Browser other questions tagged

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