How to remove trailing spaces and change encoding in char(n) columns in dynamic ExecuteQuery

流过昼夜 提交于 2021-02-17 07:07:21

问题


ASP.NET MVC Core 5 application uses Npgsql to get data from Postgres database.

Columns in database are defined as CHAR(n) type, like:

create table prpalk ( sfirmanimi char(100) );

Column types cannot be changed to varchar. Postgres database encoding is unicode. However some columns are in custom encoding which needs to be converted to unicode to be used in .NET. Those column names in database start always with word Custom.

I tried Dapper to get data but data contains trailing spaces and havent found place to specify custom mapping.

How to remove trailing spaces automatically ? Is there some event in Dapper which can use to trim all string columns and apply custom encoding when returned to caller ?

I haven't found such setting in Dapper, Npgsql or Postgres database. Column types and contents in database cannot changed to varchar due to compatibility with existing code.

Currenty I'm using special ExecuteQuery method written by Marc Gravell many years ago. It allows to specify mapping delegate which is called for conversion:

    ConvertValue += (sender, args) =>
    {
        if (args.Value != null && args.Value != DBNull.Value && args.Value is string)
        {
            args.Value = ((string)args.Value).TrimEnd();
            IDataRecord rec = args.Record; // sender as IDataRecord;
            args.Value = StringLocalizer.ToRus(rec.GetName(args.Ordinal), args.Value.ToString());
        }
    };

However it does not support dynamic property values. Dapper has ExecuteQuery method which returns dynamic properies. However custom mapping is not supported.

Is it reasonable to change code to support which or should special method created which post-processes returned IEnumerable results by trimming spaces and converting Custom property values.

EF Core is also used, maybe this can help.

来源:https://stackoverflow.com/questions/65770554/how-to-remove-trailing-spaces-and-change-encoding-in-charn-columns-in-dynamic

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