不包含' GetInt32'的定义并且没有接受第一个参数的扩展方法

时间:2015-03-15 07:55:20

标签: c# winforms

我正在创建一个发票窗口表单应用,但是当我将GetInt32放在代码中时,我遇到了问题:

 private void StoreData()
    {
        int invoiceID;
        int Item_Id;
        int quantity;

        using (var con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\oo\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30"))
        {
            con.Open();
            using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = @"insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total); select SCOPE_IDENTITY() as InvoiceID;";
                cmd.Parameters.AddWithValue("@subtotal", subtotal);
                cmd.Parameters.AddWithValue("@tax", totalTaxes);
                cmd.Parameters.AddWithValue("@total", total);
                using (var reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                        invoiceID = cmd.GetInt("InvoiceID");
                    //invoiceID =(int)cmd.Parameters["@InvoiceID"].Value;
                }
            }
            foreach (var item in OrderItems.Rows)
            {
                using (var cmd = con.CreateCommand())
                {
                    cmd.CommandText = @"insert into InvoiceItem(InvoiceID,ItemID,quantity) values (@InvoiceID,@ItemID,@quantity);";
                    cmd.Parameters.AddWithValue("@InvoiceID", invoiceID);
                    cmd.Parameters.AddWithValue("@ItemID", Item_Id);
                    cmd.Parameters.AddWithValue("@quantity", quantity);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }

我尝试了invoiceID = cmd.SqlDataReader.GetInt32("InvoiceID");invoiceID = cmd.SqlDataReader.GetInt32("InvoiceID");,但无效。

1 个答案:

答案 0 :(得分:1)

GetInt32期望列的序号位置。要改为指定列名,可以使用SqlDataReader上的string indexerinvoiceID = (int)reader["InvoiceID"]; 接受列名:

InvoiceID

这假定您的GetOrdinal列不可为空。如果是,则应使用IsDBNull和{{1}}代替。