1

Hi all I'm trying to insert some values to the database using mvc in asp.net. I heard that it would be good use objects when inserting data. So How can I achieve this using a List of objects through properties designed in a class.

Have a class called,

public class Customer
    {
        public string Name { get; set; }
        public string Company { get; set; }
        public int Telephone { get; set; }
        public string Email { get; set; }
        public int Id { get; set; }
    }

So I have a another class which simply do the sql commands

DBAccess.cs

public List<Customer> AddCustomers(string spName)
        {
            List<Customer> customers = new List<Customer>();

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = spName;
        }

I know that using Idata Reader using can get the values in a database like this

IDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                Customer cus = new Customer();

                cus.Name = reader["cus_name"].ToString();
                cus.Id = Convert.ToInt32(reader["cid"]);

                customers.Add(cus);
            }

How do I insert data back to the database using such a scenario? Help would be appreciated.

10
  • Is it update or insert? DataTable can be saved in database easily using SqlBulkCopy Commented Jul 29, 2016 at 6:03
  • @Sami Insert data to database :) Commented Jul 29, 2016 at 6:06
  • @AshaneAlvis. see this stackoverflow.com/a/12939934/4873601 Commented Jul 29, 2016 at 6:13
  • you can write one StoredProcedure for insert Commented Jul 29, 2016 at 6:13
  • @AwaisMahmood I wanted to know that if we can achieve this using a List of objects Like List<Customer> Commented Jul 29, 2016 at 6:17

1 Answer 1

3

At the base you have to make an SQL insert command to insert into DB. So, you could try the following. This method will get the list and table name as a parameter. Inside the loop reflection is used to insert the values in key value pair list.

public static bool Insert(List<YourModel> datas, string table)
{
    bool result = false;
    List<KeyValuePair<string, string>> values = new List<KeyValuePair<string, string>>();

    SqlConnection con = new SqlConnection("your connection string");
    con.Open();

    try
    {
        foreach (var data in datas)
        {

            values.Clear();
            foreach (var item in data.GetType().GetProperties())
            {          
                 values.Add(new KeyValuePair<string, string>(item.Name, item.GetValue(data).ToString()));
            }

            string xQry = getInsertCommand(table, values);
            SqlCommand cmdi = new SqlCommand(xQry, con);
            cmdi.ExecuteNonQuery();
        }
        result = true;
    }
    catch(Exception ex)
    { throw ex; }
    finally { con.Close(); }
    return result;
}

In the following method the key value pair list will be passed to another function to make the insert command.

private static string getInsertCommand(string table, List<KeyValuePair<string, string>> values)
{
    string query = null;
    query += "INSERT INTO " + table + " ( ";
    foreach (var item in values)
    {
        query += item.Key;
        query += ", ";
    }
    query = query.Remove(query.Length - 2, 2);
    query += ") VALUES ( ";
    foreach (var item in values)
    {
        if (item.Key.GetType().Name == "System.Int") // or any other numerics
        {
            query += item.Value;
        }
        else
        {
            query += "'";
            query += item.Value;
            query += "'";
        }
        query += ", ";
    }
    query = query.Remove(query.Length - 2, 2);
    query += ")";
    return query;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.