Hi mahesh213,
Please refer below sample.
Model
public class Customers
{
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public int Salary { get; set; }
}
Namescapces
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
SaveColumnsAndValuesToDB();
return View();
}
private void SaveColumnsAndValuesToDB()
{
Customers customers = new Customers { Id = 1, Name = "John Hammond", Country = "United States", Salary = 50000 };
foreach (var prop in customers.GetType().GetProperties())
{
string fieldName = prop.Name;
string value= prop.GetValue(customers, null).ToString();
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES (@oldvalue, @newvalue, @FieldName, @CreatedDate)",con))
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@oldvalue", 0);
cmd.Parameters.AddWithValue("@newvalue", value);
cmd.Parameters.AddWithValue("@FieldName", fieldName);
cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}