我在数据库中创建了标量函数 9 T9 R$ x- X0 g3 @2 a z; l4 QSET 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 = @Username RETURN @UserId END现在,我想在.NET C#或VB.NET它在代码中运行。 : Q( \, ^# k2 S( }; ?+ v: y. B; r) B& U我用实体框架试图用功能映射映射,但没有成功。我不在乎用简单的DbCommand要做到这一点,问题是我没有得到任何结果(这个函数存在于Entities类中): 5 y1 N2 W. j3 hpublic 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发布。3 V" _) f0 I: k X
7 ]' S. d, |9 u- J; y; c" v1 i解决方案: $ @4 Y- C" x1 R1 i" T& W9 Y 在这种情况下,听起来 正确的 - Y! f/ ?& ]+ @# j- [( T该方法是使用实体框架的功能来定义.NET将函数映射到您身上UDF,但我想我明白为什么你在用它。ADO没有得到预期的结果.NET做到这一点-: H+ k/ [3 g. t; E4 @
你告诉它你在调用存储过程,但实际上是在调用函数。6 l1 P! ~1 o4 Z9 h1 D
试试这个:; E4 O9 u* j' C8 ^; Z1 t
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