我在数据库中创建了标量函数
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代码中运行它。
我使用 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;
}
有什么解决办法吗?
欢迎使用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
}
}
关于.net - 如何在.NET中使用SQL用户定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1056390/