How to use SQL user defined functions in .NET?

前端 未结 2 1382
广开言路
广开言路 2020-12-10 06:24

I created a scalar function in the DB

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fn_GetUserId_Username]
    (
    @Username varch         


        
2条回答
  •  萌比男神i
    2020-12-10 06:45

    It sounds like the right way in this case is to use the functionality of the entity framework to define a .NET function and map that to your UDF, but I think I see why you don't get the result you expect when you use ADO.NET to do it -- you're telling it you're calling a stored procedure, but you're really calling a function.

    Try this:

    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 
        }
    }
    

提交回复
热议问题