Can AnsiStrings be used by default with Dapper?

十年热恋 提交于 2019-12-18 13:09:30

问题


I'm using Dapper against a database where strings are stored primarily in VarChar columns. By default Dapper uses NVarChar parameters when generating queries and while I can wrap each and every string parameter I use with DbString it'd be great to use AnsiStrings by default and use DbString for the NVarChar case.

I tried changing the type map in the Dapper source from DbType.String to DbType.AnsiString however that seems to cause an error in the IL generation for the parameters delegate (throws an InvalidProgramException).

Is there an easier way to do this?

Update

Just changing the typeMap was not sufficient I needed to alter some if (dbType == DbType.String) checks too. Now it works!


回答1:


You can accomplish this without modifying the source code.

Dapper.SqlMapper.AddTypeMap(typeof(string), System.Data.DbType.AnsiString);

Setting this once will adjust all of your strings to varchar.




回答2:


To use ansistrings by default I had to (referring to Dapper 1.3 source from NuGet):

  • Alter the type map to use DbType.AnsiString on L164 instead of DbType.String
  • In the method CreateParamInfoGenerator change the checks on L960, L968, L973 to include DbType.AnsiString as well as DbType.String.

The problem with the invalid IL seemed to be that the later branch of the code on L1000 checks for typeof(string) whereas the preceeding branches use DbType.

Doing that everything is peachy again - no more index scans!



来源:https://stackoverflow.com/questions/6386069/can-ansistrings-be-used-by-default-with-dapper

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