Store Procedure,存儲過(guò)程。也是被別人寫(xiě)過(guò)的東西。我習慣性先看別人都寫(xiě)了點(diǎn)啥,然后才開(kāi)始想看看自己還要寫(xiě)點(diǎn)啥。那就先談?wù)勊cudf的區別吧。
在
Linq To Sql進(jìn)階系列(四)User Define Function篇 中,我們提到了兩者的差別。比如Store Procedure支持多個(gè)rowset的,而udf不行。他們還有一些其他的差別。Store Procedure只能返回整型,而udf可以是其他類(lèi)型,比如char等,除個(gè)別類(lèi)型外,比如imager類(lèi)型,是不可以做為udf的返回類(lèi)型的。Store Procedure支持Out Parameter而udf沒(méi)有。
1, SingleResultSet
我們先來(lái)看這個(gè)sprocs.
CREATE PROCEDURE [dbo].[Customers By City]
-- Add the parameters for the stored procedure here
(@param1 NVARCHAR(20))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT CustomerID, ContactName, CompanyName, City from Customers as c where c.City=@param1
END 其生成的code如下。
[Function(Name="dbo.[Customers By City]")]
public ISingleResult<Customers_By_CityResult> Customers_By_City([Parameter(DbType="NVarChar(20)")] string param1)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), param1);
return ((ISingleResult<Customers_By_CityResult>)(result.ReturnValue));
} 這里Customers_By_CityResult是這個(gè)sprocs的影射類(lèi)。但你可以在OR Designer里調整。如圖,
選中該函數后,右擊屬性。就可以使用其他影射類(lèi)。但是Linq會(huì )對返回的rowset做檢查,如果發(fā)現返回結果和影射不匹配它會(huì )報錯。而且一旦更改了,當你需要改回去的時(shí)候,你只能在Designer中刪掉此sprocs,然后重新拖過(guò)來(lái)。
調用它很簡(jiǎn)單,就當作一個(gè)函數,但是,這里和普通的linq語(yǔ)句不一樣的地方是,它不是延遲加載的。
DataClasses1DataContext db = new DataClasses1DataContext();
db.Log = Console.Out;
var q = db.Customers_By_City("London"); 正因它不是延遲加載的,所以,linq可以對他進(jìn)行簡(jiǎn)單的內聯(lián)操作,比如
DataClasses1DataContext db = new DataClasses1DataContext();
db.Log = Console.Out;
var q = from c in db.Customers_By_City("London")
orderby c.City
select c; 注意的時(shí),這里是Linq To Object而不是Linq To Sql。
2, MultipleResultSets
看下面的例子
CREATE PROCEDURE [dbo].[Get Customer And Orders](@CustomerID nchar(5))
-- Add the parameters for the stored procedure here
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT * FROM Customers AS c WHERE c.CustomerID = @CustomerID
SELECT * FROM Orders AS o WHERE o.CustomerID = @CustomerID
END 使用OR designer對其影射,其dbml為
<Function Name="dbo.[Get Customer And Orders]" Method="Get_Customer_And_Orders">
<Parameter Name="CustomerID" Parameter="customerID" Type="System.String" DbType="NChar(5)" />
<ElementType Name="Get_Customer_And_OrdersResult">
<Column Name="CustomerID" Type="System.String" DbType="NChar(5) NOT NULL" CanBeNull="false" />
<Column Name="CompanyName" Type="System.String" DbType="NVarChar(40) NOT NULL" CanBeNull="false" />
<Column Name="ContactName" Type="System.String" DbType="NVarChar(30)" CanBeNull="true" />
<Column Name="ContactTitle" Type="System.String" DbType="NVarChar(30)" CanBeNull="true" />
<Column Name="Address" Type="System.String" DbType="NVarChar(60)" CanBeNull="true" />
<Column Name="City" Type="System.String" DbType="NVarChar(15)" CanBeNull="true" />
<Column Name="Region" Type="System.String" DbType="NVarChar(15)" CanBeNull="true" />
<Column Name="PostalCode" Type="System.String" DbType="NVarChar(10)" CanBeNull="true" />
<Column Name="Country" Type="System.String" DbType="NVarChar(15)" CanBeNull="true" />
<Column Name="Phone" Type="System.String" DbType="NVarChar(24)" CanBeNull="true" />
<Column Name="Fax" Type="System.String" DbType="NVarChar(24)" CanBeNull="true" />
</ElementType>
</Function> 用sqlmetal對它做影射,生成dbml為
<Function Name="dbo.Get Customer And Orders" Method="GetCustomerAndOrders">
<Parameter Name="CustomerID" Parameter="customerID" Type="System.String" DbType="NChar(5)" />
<ElementType Name="GetCustomerAndOrdersResult1">
<Column Name="CustomerID" Type="System.String" DbType="NChar(5)" CanBeNull="true" />
<Column Name="CompanyName" Type="System.String" DbType="NVarChar(40)" CanBeNull="true" />
<Column Name="ContactName" Type="System.String" DbType="NVarChar(30)" CanBeNull="true" />
<Column Name="ContactTitle" Type="System.String" DbType="NVarChar(30)" CanBeNull="true" />
<Column Name="Address" Type="System.String" DbType="NVarChar(60)" CanBeNull="true" />
<Column Name="City" Type="System.String" DbType="NVarChar(15)" CanBeNull="true" />
<Column Name="Region" Type="System.String" DbType="NVarChar(15)" CanBeNull="true" />
<Column Name="PostalCode" Type="System.String" DbType="NVarChar(10)" CanBeNull="true" />
<Column Name="Country" Type="System.String" DbType="NVarChar(15)" CanBeNull="true" />
<Column Name="Phone" Type="System.String" DbType="NVarChar(24)" CanBeNull="true" />
<Column Name="Fax" Type="System.String" DbType="NVarChar(24)" CanBeNull="true" />
</ElementType>
<ElementType Name="GetCustomerAndOrdersResult2">
<Column Name="OrderID" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="CustomerID" Type="System.String" DbType="NChar(5)" CanBeNull="true" />
<Column Name="EmployeeID" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="OrderDate" Type="System.DateTime" DbType="DateTime" CanBeNull="true" />
<Column Name="RequiredDate" Type="System.DateTime" DbType="DateTime" CanBeNull="true" />
<Column Name="ShippedDate" Type="System.DateTime" DbType="DateTime" CanBeNull="true" />
<Column Name="ShipVia" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="Freight" Type="System.Decimal" DbType="Money" CanBeNull="true" />
<Column Name="ShipName" Type="System.String" DbType="NVarChar(40)" CanBeNull="true" />
<Column Name="ShipAddress" Type="System.String" DbType="NVarChar(60)" CanBeNull="true" />
<Column Name="ShipCity" Type="System.String" DbType="NVarChar(15)" CanBeNull="true" />
<Column Name="ShipRegion" Type="System.String" DbType="NVarChar(15)" CanBeNull="true" />
<Column Name="ShipPostalCode" Type="System.String" DbType="NVarChar(10)" CanBeNull="true" />
<Column Name="ShipCountry" Type="System.String" DbType="NVarChar(15)" CanBeNull="true" />
</ElementType>
</Function> 仔細比較他們的區別哦。“好像名字不一樣呢”。暈倒??粗饕?。第一個(gè)只有一個(gè)ElementType子項,而第二個(gè)有2個(gè)。這個(gè)地方其實(shí)可以說(shuō)是OR designer的一個(gè)bug。要想修改這個(gè)bug,需要更改一個(gè)設計,而推動(dòng)更改設計,比較麻煩。但并不是不能改。如果你認為這個(gè)真的很需要,而且對你很重要,你更喜歡用or designer的話(huà),我建議你去下面的社區發(fā)帖子。
http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=123&SiteID=1要求更改此處的問(wèn)題。因為,我已經(jīng)無(wú)力推動(dòng)他們修復該bug,ms更樂(lè )意聽(tīng)來(lái)自客戶(hù)的聲音,說(shuō)不定你會(huì )成功的哦,還有獎勵的哦。
這個(gè)sprocs準確的影射代碼為
[Function(Name="dbo.Get Customer And Orders")]
[ResultType(typeof(GetCustomerAndOrdersResult1))]
[ResultType(typeof(GetCustomerAndOrdersResult2))]
public IMultipleResults GetCustomerAndOrders([Parameter(Name="CustomerID", DbType="NChar(5)")] string customerID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), customerID);
return ((IMultipleResults)(result.ReturnValue));
} 對于MultipleResultSets的sprocs,大家更關(guān)注如何取其返回結果。其實(shí)很簡(jiǎn)單,按順序,一個(gè)rowset,一個(gè)rowset的取。這個(gè)順序和你sprocs里的順序是一樣的。
IMultipleResults result = db.GetCustomerAndOrders("SEVES");
IEnumerable<CustomerResultSet> customer = result.GetResult<CustomerResultSet>();
IEnumerable<OrdersResultSet> orders = result.GetResult<OrdersResultSet>();
如果,你很貪心,再加一行的話(huà),
IEnumerable<CustomerResultSet> customer = result.GetResult<CustomerResultSet>();
報錯咯,越界了。沒(méi)有那么多,你問(wèn)要也不給。
3,OutParameters
似乎沒(méi)有什么好講的,很簡(jiǎn)單,當作ref 的函數參數輸出的。其也只是在生成的函數里加了這么一句
outParameter = ((System.
Nullable<
int>)(result.GetParameterValue(1))); 調用result.GetParameterValue方法,大家要記住這個(gè)哦。
4,Return Value
呀,把return value丟那里了。的確,Linq曾舍棄過(guò)return value.后來(lái)在qa的堅持下,dev們決定保留了它。但是,需要你自己去更改code,才能獲得。我們可以從下面這個(gè)sprocs上獲得靈感。
CREATE PROCEDURE [dbo].[CustOrderTotal]
@CustomerID nchar(5),
@TotalSales money OUTPUT
AS
SELECT @TotalSales = SUM(OD.UNITPRICE*(1-OD.DISCOUNT) * OD.QUANTITY)
FROM ORDERS O, "ORDER DETAILS" OD
where O.CUSTOMERID = @CustomerID AND O.ORDERID = OD.ORDERID
其影射的code為
[Function(Name="dbo.CustOrderTotal")]
public int CustOrderTotal([Parameter(Name="CustomerID", DbType="NChar(5)")] string customerID, [Parameter(Name="TotalSales", DbType="Money")] ref System.Nullable<decimal> totalSales)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), customerID, totalSales);
totalSales = ((System.Nullable<decimal>)(result.GetParameterValue(1)));
return ((int)(result.ReturnValue));
} 因為該sprocs并沒(méi)有rowset返回,其最后只剩返回值了。其是將result.RenturnValue強制轉化為int型,以得到sprocs的整形返回值。那對于SingleResultSet和MultipleResultSets的,該如何獲取它的返回值呢?那只有自己動(dòng)手,修改code了。就是自己強制轉換,而后通過(guò)out 參數輸出。比如用第一個(gè)sprocs
[Function(Name = "dbo.[Customers By City]")]
public ISingleResult<Customers_By_CityResult1> Customers_By_City([Parameter(DbType = "NVarChar(20)")] string param1)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), param1);
return ((ISingleResult<Customers_By_CityResult1>)(result.ReturnValue));
}
public ISingleResult<Customers_By_CityResult1> Customers_By_City2(string para, out int returnValue)
{
ISingleResult<Customers_By_CityResult1> result = this.Customers_By_City(para);
returnValue = (int)result.ReturnValue;
return ((ISingleResult<Customers_By_CityResult1>)result);
} 測試一下
DataClasses1DataContext db = new DataClasses1DataContext();
db.Log = Console.Out;
int returnValue = -1;
var q = db.Customers_By_City2("London",out returnValue);
Console.WriteLine(returnValue); 也可以使用result.GetParameterValue方法獲取返回值。只是linq會(huì )檢查影射函數的參數個(gè)數。這個(gè)使用起來(lái)比較麻煩??梢赃@么使用,比如,有一個(gè)sprocs,有2個(gè)參數,其中有一個(gè)out的參數。這個(gè)out的參數,可以不做任何操作。在影射后,修改其code。這兩個(gè)參數的位標是從0開(kāi)始,依次遞增。其code本來(lái)為outParameter = ((System.
Nullable<
int>)(result.GetParameterValue(1))); 將其索引修改位為2,就是return value了。再大了又該拋了。