Click here to Skip to main content
15,893,722 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi I am working on asp.net mvc3 based product.
and don't wanna use entity framework in my product for database access
I have to use basic database connectivity approach.

can anyone give me solution of this problem.how to use it .

With Warm Regards,
Gaurav ebay
Posted

1 solution

In that case, use straight ADO.NET code. Here is some sample code that we sometimes use to read and write data in a SQL database:

C#
public static System.Data.DataTable ReadData(string connectionString, string sqlQuery, Dictionary<string,> parameters = null)
{
    DataTable myTable = new DataTable();
    using (SqlConnection cnn = new SqlConnection(connectionString))
    {
        cnn.Open();

        using (SqlCommand myCommand = new SqlCommand())
        {
            SqlParameter param;
            myCommand.CommandText = sqlQuery;

            //Loops through each parameter in the dictionary
            //and adds it to the parameters list
            if (parameters != null)
            {
                foreach (var entry in parameters)
                {
                    param = new SqlParameter();
                    param.ParameterName = entry.Key;
                    param.Value = entry.Value;
                    myCommand.Parameters.Add(param);
                }
            }

            myCommand.Connection = cnn;

            using (SqlDataReader reader = myCommand.ExecuteReader())
            {
                myTable.Load(reader);
            }
        }
    }
    return myTable;
}

public static int WriteData(string connectionString, string sqlQuery, Dictionary<string,> parameters = null)
{
    using (SqlConnection cnn = new SqlConnection(connectionString))
    {
        cnn.Open();

        using (SqlCommand myCommand = new SqlCommand())
        {
            SqlParameter param;
            myCommand.CommandText = sqlQuery;

            //Loops through each parameter in the dictionary
            //and adds it to the parameters list
            if (parameters != null)
            {
                foreach (var entry in parameters)
                {
                    param = new SqlParameter();
                    param.ParameterName = entry.Key;
                    param.Value = entry.Value;
                    myCommand.Parameters.Add(param);
                }
            }

            myCommand.Connection = cnn;

            return myCommand.ExecuteNonQuery();
        }
    }

}

To use this, just pass in the connection string, the SQL query, and a Dictionary list of parameters. Adding a parameter to the Dictionary would look like this:

C#
parameters.Add("@UserID", "14");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900