How should I access SQL Server from a WCF service solution?

.net, c#, sql-server, wcf

Solution

- Save your connection string in the configuration file.

- Connect to the Database as much as you like, Connection Pool will take care of that you do not have to worry about it.

Always use `using` when dealing with sql connections.

`Using (sqlConn = new SqlConnection(ConnString)) { }`

Make your own POCOs to return the result to the client, you can either make them in seperate assembly and share it in both projects (WCF and client) or you can just add them to the WCF and when you create the proxy at the client side you will have access to them.

Here is a sample layout:

public Poco Foo(long id)
{
    try
    {
        using (SqlConnection SqlConn = new SqlConnection(ConnString))
        {
            // execute your commands and do your stuff
            return Poco;
        }
    }
    catch (Exception ex)
    {
        Logger.Log(ex.ToString());
        return null;
    }
}

UPDATE

Here is an example of how to return a 'DataSet` to the client, I do not recommend this but it will work:

public DataSet Foo(long id)
    {
        try
        {
            using (SqlConnection SqlConn = new SqlConnection(ConnString))
            {
                SqlCommand sqlCmd = new SqlCommand("Select * From users where userid=@id", SqlConn);
                sqlCmd.Parameters.Add("@id", SqlDbType.BigInt).Value = id;
                DataSet ds = new DataSet();
                using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd))
                {
                    da.Fill(ds, "Users");
                }

                return ds;
            }
        }
        catch (Exception ex)
        {
            Logger.Log(ex.ToString);
            return null;
        }
    }

Problem

I have some existing WCF code that accesses SQL Server 2005, but honestly I've come to mistrust that developer's methods, so I want to know how this should be done correctly and professionally. I need to be able to pass an SQL statement to a method (within the WCF service, not from the client) that returns the resultant dataset (to the method in WCF that called it, not the client). I'm not interested in entity frameworks or other abstraction layers. I need to run SQL, DML, and hopefully DDL too. I also want to know how to manage the connections. Please point out your thoughts on better alternatives if you feel like it. I'm prepared to listen.

Original source