enterprise library dbcommand AddInParameter method

北战南征 提交于 2019-12-11 07:46:46

问题


I have been using enterprise library since long time. We are changing column type varchar to nvarchar in database to support different language. We do have some legacy code that is using traditional way to connect to database like using command object. In that code, when creating sqlparameters, parameter's datatype is specified whether it is int or varchar. It's easy to change from varchar to nvarchar there.

But I am wondering about while using enterprise library where we specify .net datatype like string and I believe enterprise library converts that type into sqldatatype internally when calling stored procedure.

db.AddInParameter(cmd, "@SortOrder", DbType.String, SortOrder)

What datatype enterprise library converts internally? varchar or nvarchar? Is it safe to use nvarchar all over the places in legacy code we have?


回答1:


As I said in comments, No need to worry about datatype converting .net will take care of it and handle it automatically. ADO.net is able to convert String datatype to varchar, nvarchar, char, ntext, text data types in SqlServer. Specifying stored-procedures data types inform ADO.net to convert data to its appropriate data type in SqlServer.

why we specify datatype when creating a sqlparameter object or calling AddInParameter if .net takes care of that?

EDIT : Base on your question in comments, there is :

db.Parameters.AddWithValue("@SortOrder", SortOrder);

which is not necessary to specify your input parameter's data type.




回答2:


I assume you are using SQL Server.

DbType.String is for nvarchar while DbType.AnsiString is for varchar. http://msdn.microsoft.com/en-us/library/system.data.dbtype.aspx

Since you are calling a stored procedure, your parameter gets automatically converted to whatever string type is specified in the stored procedure. For example if the input is DbType.String but the parameter is varchar, SQL Server converts it for you. Don't do it in reverse though (in the code in DbType.AnsiString but the stored procedure expects nvarchar) because you will only get the ansi chars in the stored procedure.

//Don't do this! you will get 'h?ello' in the SP instead of 'hܒello'
SqlParameter("input", "h\u0712ello") { DbType = System.Data.DbType.AnsiString });

Also, in EntLib, there is a way to call stored procedures without needing to specify the parameter names and data type. Like so:

//calls AddToInventory stored procedure
//the 2 parameters are automatically mapped.
db.ExecuteNonQuery("AddToInventory", 1, "Life Jacket");


来源:https://stackoverflow.com/questions/7235135/enterprise-library-dbcommand-addinparameter-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!