Dot-Net
如何在 .NET 中使用 SQL 使用者定義函式?
我在數據庫中創建了一個標量函式
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER FUNCTION [dbo].[fn_GetUserId_Username] ( @Username varchar(32) ) RETURNS int AS BEGIN DECLARE @UserId int SELECT @UserId = UserId FROM [User] WHERE Username = @Username RETURN @UserId END現在我想在我的 .NET C# 或 VB.NET 程式碼中執行它。
我使用實體框架,我試圖用函式映射來映射它,但我沒有成功。我不在乎用簡單的 DbCommand 來做,問題是我沒有得到任何結果(該函式存在於 Entities 類中):
public int GetUserIdByUsername(string username) { EntityConnection connection = (EntityConnection)Connection; DbCommand com = connection.StoreConnection.CreateCommand(); com.CommandText = "fn_GetUserId_Username"; com.CommandType = CommandType.StoredProcedure; com.Parameters.Add(new SqlParameter("Username", username)); if (com.Connection.State == ConnectionState.Closed) com.Connection.Open(); try { var result = com.ExecuteScalar(); //always null } catch (Exception e) { } return result; }有什麼解決辦法嗎?歡迎使用 C# 或 VB.NET 發表文章。
聽起來在這種情況下正確的方法是使用實體框架的功能來定義一個 .NET 函式並將其映射到您的 UDF,但我想我明白為什麼在使用 ADO 時沒有得到預期的結果.NET 來做到這一點——你告訴它你正在呼叫一個儲存過程,但你實際上是在呼叫一個函式。
試試這個:
public int GetUserIdByUsername(string username) { EntityConnection connection = (EntityConnection)Connection; DbCommand com = connection.StoreConnection.CreateCommand(); com.CommandText = "select dbo.fn_GetUserId_Username(@Username)"; com.CommandType = CommandType.Text; com.Parameters.Add(new SqlParameter("@Username", username)); if (com.Connection.State == ConnectionState.Closed) com.Connection.Open(); try { var result = com.ExecuteScalar(); // should properly get your value return (int)result; } catch (Exception e) { // either put some exception-handling code here or remove the catch // block and let the exception bubble out } }