一尘不染

如何在.NET中使用SQL用户定义的函数?

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发布。


阅读 121

收藏
2021-05-05

共1个答案

一尘不染

在这种情况下,听起来 正确的
方法是使用实​​体框架的功能来定义.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 
    }
}
2021-05-05