Shi*_*mmy 9 .net sql user-defined-functions oledbcommand
我在DB中创建了一个标量函数
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
Run Code Online (Sandbox Code Playgroud)
现在我想在.NET C#或VB.NET代码中运行它.
我使用Entity Framework,我试图用功能映射映射它,但我没有成功.我不关心用简单的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;
}
Run Code Online (Sandbox Code Playgroud)
有什么解决方案吗?C#或VB.NET中的帖子都会受到欢迎.
Jon*_*upp 17
在这种情况下,听起来正确的方法是使用实体框架的功能来定义.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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32490 次 |
| 最近记录: |