[英]How to get multiple dynamic row value into the database using asp.net mvc
public void create(account_detail c, int jobcard_id)
{
SqlConnection con = new SqlConnection(@"Data source =(LocalDB)\v11.0;AttachDbFilename=C:\Users\Wattabyte Inc\Documents\CarInfo.mdf;Integrated Security=True;");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
string additionalText = string.Empty;
bool needComma = false;
foreach (var details in c.Data)
{
if (needComma)
{
additionalText += ", ";
}
else
{
needComma = true;
additionalText += "('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "')";
}
cmd.CommandText = "insert into child_detail values " + additionalText + ";";
cmd.ExecuteNonQuery();
}
我正在使用此代碼,但它僅采用單個值,但我想將多個值保存到數據庫中。 我該如何實現?
如果您需要多個jobcard_id
請執行此操作。 請注意,這使它適合您的代碼,建議您進行一些重構,並找出一種更好的方法,因為這樣做很丑陋。
public void create(account_detail c, List<int> jobcard_ids)
{
SqlConnection con = new SqlConnection(@"Data source =(LocalDB)\v11.0;AttachDbFilename=C:\Users\Wattabyte Inc\Documents\CarInfo.mdf;Integrated Security=True;");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
string additionalText = string.Empty;
bool needComma = false;
foreach (var details in c.Data)
{
if (needComma)
{
additionalText += ", ";
}
else
{
needComma = true;
foreach(var jobcard_id in jobcard_ids)
{
additionalText += "('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "')";
if (jobcard_id != jobcard_ids.Last())
{
// We will need to comma separate the query string unless it's the last item
additionalText+= ",";
}
}
}
cmd.CommandText = "insert into child_detail values " + additionalText + ";";
cmd.ExecuteNonQuery();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.