I need to connect a WCF webservice to a SQL Server database. I need to only use SQL to access the data, no LINQ or Entity Framework.
I tried to follow this tutorial: http://www.c-sharpcorner.com/UploadFile/rohatash/inserting-data-into-database-using-wcf-service/ . The SqlConnection class seems to be what I need to use, but when I see this service method:
public string InsertUserDetails(UserDetails userInfo)
{
// ...
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Rajesh;User ID=sa;Password=wintellect");
con.Open();
SqlCommand cmd = new SqlCommand("insert into RegistrationTable(UserName,Password,Country,Email) values(@UserName,@Password,@Country,@Email)", con);
cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);
cmd.Parameters.AddWithValue("@Password", userInfo.Password);
cmd.Parameters.AddWithValue("@Country", userInfo.Country);
cmd.Parameters.AddWithValue("@Email", userInfo.Email);
int result = cmd.ExecuteNonQuery();
// ...
}
I'm worried because apparently, a database connection will be created on each request.
Here's a sample of the code structure I would like to have:
public class Service : IService
{
public Company GetCompany(int key)
{
// Get existing database connection
// SELECT * from companies where c_key=key
// Return Company instance
}
}
What structure should I use to access the data using SQL and not create a database connection on each request? Can I just make the SqlConnection instance static? I don't understand how WCF handle this, how many Service instances will be created etc.. Thank you for your help!
SqlConnectionis just a wrapper).usingstatements for theSqlCommandandSqlConnection.