Skip to content

Instantly share code, notes, and snippets.

@happyincent
Created April 1, 2023 15:03
Show Gist options
  • Save happyincent/1d18257af3a93668ebd19374debd24e8 to your computer and use it in GitHub Desktop.
Save happyincent/1d18257af3a93668ebd19374debd24e8 to your computer and use it in GitHub Desktop.
Convert string to Dapper's DbString with StringLengthAttribute and UnicodeAttribute.
public static DbString ToDbString<T>(this string value, string key, bool? IsFixedLength, int? MaxLength, bool? IsAnsi)
{
var property = typeof(T).GetProperty(key);
var attrLength = property?.GetCustomAttributes<StringLengthAttribute>().SingleOrDefault();
var maxLength = MaxLength ?? attrLength?.MaximumLength ?? DbString.DefaultLength;
var attrAnsi = property?.GetCustomAttributes<UnicodeAttribute>().SingleOrDefault();
var isAnsi = IsAnsi ?? attrAnsi?.IsUnicode switch
{
null => DbString.IsAnsiDefault,
true => false,
false => true,
};
return new DbString
{
Value = value,
Length = maxLength ,
IsFixedLength = IsFixedLength ?? false,
IsAnsi = isAnsi
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment