我正在从C#方法向SQL Server存储过程发送参数,如下所示:
public void YENI_ALM_SIFARISI_AC(
decimal TEKLIF_BEDELI2,
string REFERANS_NO,
string CARIKOD,
string CARIAD,
string ACIKLAMA,
int SUB_ID,
int DETAY_ID,
string DETAY,
decimal SUB_TEKLIF,
decimal QIYMET,
string OLCU_VAHIDI,
decimal IS_HECMI
)
{
string CS = ConfigurationManager.ConnectionStrings["Sumqayit"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("YENI_ALM_SIFARISI_AC", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@TEKLIF_BEDELI2",TEKLIF_BEDELI2);
cmd.Parameters.AddWithValue("@REFERANS_NO",REFERANS_NO);
cmd.Parameters.AddWithValue("@CARIKOD",CARIKOD);
cmd.Parameters.AddWithValue("@CARIAD",CARIAD);
cmd.Parameters.AddWithValue("@ACIKLAMA",ACIKLAMA);
cmd.Parameters.AddWithValue("@SUB_ID",SUB_ID);
cmd.Parameters.AddWithValue("@DETAY_ID",DETAY_ID);
cmd.Parameters.AddWithValue("@DETAY",DETAY);
cmd.Parameters.AddWithValue("@SUB_TEKLIF",SUB_TEKLIF);
cmd.Parameters.AddWithValue("@QIYMET",QIYMET);
cmd.Parameters.AddWithValue("@OLCU_VAHIDI",OLCU_VAHIDI);
cmd.Parameters.AddWithValue("@IS_HECMI",IS_HECMI);
con.Open();
int DataID = (int)cmd.ExecuteScalar();
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(DataID));
//cmd.ExecuteNonQuery();
con.Close();
}
}
似乎我在void参数和sqlCommand参数上复制并粘贴了相同的参数名称。有什么方法可以映射这些参数,以便我不会复制并粘贴这些参数?
答案 0 :(得分:0)
您可以使用反射。将所有函数参数包装到一个类中,您可以执行以下操作:
foreach(var prop in foo.GetType().GetProperties()) {
cmd.Parameters.AddWithValue ($"@{prop.Name}", prop.GetValue(foo, null)));
}
答案 1 :(得分:0)
public void YENI_ALM_SIFARISI_AC(
decimal TEKLIF_BEDELI2,
string REFERANS_NO,
string CARIKOD,
string CARIAD,
string ACIKLAMA,
int SUB_ID,
int DETAY_ID,
string DETAY,
decimal SUB_TEKLIF,
decimal QIYMET,
string OLCU_VAHIDI,
decimal IS_HECMI
)
{
var parameters = new foo();
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("YENI_ALM_SIFARISI_AC", con);
foreach (var prop in parameters.GetType().GetProperties())
{
cmd.Parameters.AddWithValue($"@{prop.Name}", prop.GetValue(parameters, null));
}
con.Open();
int DataID = (int)cmd.ExecuteScalar();
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(DataID));
//cmd.ExecuteNonQuery();
con.Close();
}
}
public class foo
{
decimal TEKLIF_BEDELI2 { get; set; }
string REFERANS_NO { get; set; }
string CARIKOD { get; set; }
string CARIAD { get; set; }
string ACIKLAMA { get; set; }
int SUB_ID { get; set; }
int DETAY_ID { get; set; }
string DETAY { get; set; }
decimal SUB_TEKLIF { get; set; }
decimal QIYMET { get; set; }
string OLCU_VAHIDI { get; set; }
decimal IS_HECMI { get; set; }
}
我确实那样。它是.asmx文件中的一种网络方法。但是仍然即时复制和粘贴参数两次。