开发者

Stored procedure parameter names and Entity Framework

开发者 https://www.devze.com 2023-03-02 03:51 出处:网络
I\'ve generated an Entity Framework model from an SQL Server 2005 database and started to import stored procedures. So far so good, but one of the stored procedures throws an exception when I try to r

I've generated an Entity Framework model from an SQL Server 2005 database and started to import stored procedures. So far so good, but one of the stored procedures throws an exception when I try to run it:

Procedure or function 'csp_getCoworker' expects parameter '@@firstname'开发者_高级运维, which was not supplied.

Here is the signature for the stored procedure:

ALTER PROCEDURE [dbo].[csp_getCoworker](
@@firstname nvarchar(32),
@@lastname nvarchar(32),
@@businessarea nvarchar(512),
@@location nvarchar(512)
)

And here is the code generated by Entity Framework

ObjectParameter p_firstnameParameter;
if (p_firstname != null)
{
    p_firstnameParameter = new ObjectParameter("p_firstname", p_firstname);
}
    else
{
     p_firstnameParameter = new ObjectParameter("p_firstname", typeof(global::System.String));
}
[...]
return base.ExecuteFunction<csp_getCoworker_Result2>("csp_getCoworker", p_firstnameParameter, p_lastnameParameter, p_businessareaParameter, p_locationParameter);

Is it the double @-characters in the parameter name that's messing things up?


I just tested this because it is very uncommon scenario.

The stored procedure follows very strange naming convention because @@ should not be used. It is by default used by some SQL server system variables and should not be used for anything else. Using @x as parameter of stored procedure defines a parameter x but using @@x will define parameter @x - @ is part of parameter name!

This is a very big problem in C# because @ is escape character used to define names of variables same as reserved keywords. For example:

string @string = "abc";

defines variable named string. Variable name cannot start with @.

Entity framework deals with this by replacing all @ with _ and prefixing parameter's name with p directly in SSDL. The reason is that function imports created from SSDL mapped stored procedure must have parameters with the same name as the procedure but in the same time @ is not allowed starting character. If you try to modify EDMX manually it will fail its own XSD validation because @ is not allowed starting character for identifiers defined in CSDL.

Even this can probably be considered as a bug it is more about missing possibility to change the name of the parameter in CSDL. At the moment this is by design and only way is to correct names of parameters in SQL stored procedure.

0

精彩评论

暂无评论...
验证码 换一张
取 消