C#: DbType.String versus DbType.AnsiString

前端 未结 4 1446
时光说笑
时光说笑 2021-02-04 00:32

I have taken over some C# code.

The code is hitting a database with some SQL which uses parameters.

All of the string parameters are typed as

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 01:17

    Why would you use DbType.AnsiString instead of DbType.String?

    Short answer: When your SqlParameter is pointing to a varchar (or char) database column you would use DbType.AnsiString. When you point to a nvarchar column, use DbType.String because its Unicode.

    Longer answer: If these are not mapped accurately (e.g. pointing DbType.String to a varchar(nn) column, you will see CONVERT_IMPLICIT warnings in your query plans as described by Pinal Dave here: https://blog.sqlauthority.com/2018/06/11/sql-server-how-to-fix-convert_implicit-warnings/

    In my case the SqlParameter.Size property also seemed to be important: to completely eliminate CONVERT_IMPLICIT warnings I had to map DbType and Size correctly. The default Size if omitted "is inferred from the actual size of the specified parameter value"(1) which will usually mismatch the real column size definition and that raises a warning as well.

    1. https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparameter.size?view=netframework-4.7.2

提交回复
热议问题