如何在.NET中使用SQL用户定义的函数?
发布时间:2020-12-12 06:48:09 所属栏目:MsSql教程 来源:网络整理
导读:我在DB中创建了一个标量函数 SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER FUNCTION [dbo].[fn_GetUserId_Username] ( @Username varchar(32) )RETURNS intAS BEGIN DECLARE @UserId int SELECT @UserId = UserId FROM [User] WHERE Username = @User
我在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 现在我想在.NET C#或VB.NET代码中运行它. 我使用Entity Framework,我试图用功能映射映射它,但我没有成功. 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; } 有什么解决方案吗? 解决方法在这种情况下,听起来正确的方法是使用实??体框架的功能来定义.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 } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |