透過Partial Class取得預存程序的傳回值
Visual Studio會為NorthwindDataSet.xsd中的DataTable/TableAdapter建立對應的類別(儲存在*. NorthwindDataSet.Designer.cs),觀察這個檔案中的程式,您會發現TableAdapter下的每個指令都會依出現順序記錄在名為CommandCollection的集合中,例如InsertProduct這個指令出現在第二個, this.CommandCollection[1]代表的就是它(索引值從0開始)。
但這個集合是Private的,因此外部程式無法存取指令的回傳值,不過沒關係,我們可以建立一個與ProductsTableAdapter同名、同命名空間的部分類別,自行加入額外的Public成員,在本例中是個名為InsertProductReturnValue的唯讀屬性,讓外部程式可以取得所需指令的回傳值。如下:
namespace SPReturnValueApp.NorthwindDataSetTableAdapters
{
public partial class ProductsTableAdapter
{
public int InsertProductReturnValue{
get {
int result = -1;
if (this.CommandCollection[1].Parameters["@RETURN_VALUE"].Value != null)
result = (int)this.CommandCollection[1].Parameters["@RETURN_VALUE"].Value;
return result;
}
}
}
} |
撰寫測試程式
您可以建立一個Console應用程式,撰寫如下測試程式:
namespace SPReturnValueApp
{
class Program
{
static void Main(string[] args)
{
NorthwindDataSetTableAdapters.ProductsTableAdapter dap = new NorthwindDataSetTableAdapters.ProductsTableAdapter();
dap.InsertProduct("咖啡", 20);
int productId = dap.InsertProductReturnValue;
Console.WriteLine("新增產品的編號:{0}",productId);
}
}
}
|
首先建立一個ProductsTableAdapter物件-dap,接著呼叫InsertProduct加入一個新產品-產品名稱:咖啡、單價:20,之後便可呼叫新增的唯讀屬性InsertProductReturnValue取出新產品的編號。
|