我有以下内容,我可以让它按我的意愿工作,但我认为我做错了,你能解释一下如何以更有效的方式完成吗?同时也在同一个方法中循环Categories
并执行相同的操作。Districts
Insert()
提前致谢。
#region Methods
public int Insert(List<District> Districts, List<Category> Categories)
{
StringBuilder sqlString = new StringBuilder("INSERT INTO Stores (name, image) VALUES (@Name, @Image);");
using (SqlConnection sqlConnection = new
SqlConnection(ConfigurationManager.ConnectionStrings["OahuDB"].ConnectionString))
{
SqlCommand sqlCommand = new SqlCommand(sqlString.ToString(), sqlConnection);
sqlCommand.Parameters.AddWithValue("@Name", this.Name);
sqlCommand.Parameters.AddWithValue("@Image", this.Image);
sqlConnection.Open();
int x = (int)sqlCommand.ExecuteScalar();
sqlString.Clear();
sqlCommand.Parameters.Clear();
foreach (District item in Districts)
{
sqlString.AppendLine("INSERT INTO districts_has_stores (district_id, store_id) VALUES (@DistrictID, @StoreID);");
sqlCommand.CommandText = sqlString.ToString();
sqlCommand.Parameters.AddWithValue("@DistrictID", item.ID);
sqlCommand.ExecuteNonQuery();
}
return x;
}
}
编辑
通过执行以下操作来实现上述目标是错误的吗?
sqlString.Clear();
sqlCommand.Parameters.Clear();
sqlString.AppendLine("INSERT INTO districts_has_stores (district_id, store_id) VALUES (@DistrictID, @StoreID);");
sqlCommand.CommandText = sqlString.ToString();
sqlCommand.Parameters.AddWithValue("@StoreID", x);
foreach (District item in Districts)
{
sqlCommand.Parameters.AddWithValue("@DistrictID", item.ID);
sqlCommand.ExecuteNonQuery();
}
sqlString.Clear();
sqlCommand.Parameters.Clear();
sqlString.AppendLine("INSERT INTO categories_has_stores (category_id, store_id) VALUES (@CategoryID, @StoreID);");
sqlCommand.CommandText = sqlString.ToString();
sqlCommand.Parameters.AddWithValue("@StoreID", x);
foreach (Category item in Categories)
{
sqlCommand.Parameters.AddWithValue("@CategoryID", item.ID);
sqlCommand.ExecuteNonQuery();
}