Advertisement
Lord_Ownix

Simple Dapper Mapper From StackOverflow

Sep 18th, 2023
883
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.02 KB | Source Code | 0 0
  1. async Task Main()
  2. {
  3.     // https://stackoverflow.com/a/65183485/1777780
  4.     // override TypeMapProvider to return custom map for every requested type
  5.     Dapper.SqlMapper.TypeMapProvider = type =>
  6.    {
  7.        var fallback = new DefaultTypeMap(type);
  8.        return new CustomPropertyTypeMap(type, (t, column) =>
  9.        {
  10.            var property = t.GetProperties().FirstOrDefault(prop =>
  11.                prop.GetCustomAttributes(typeof(ColumnAttribute))
  12.                    .Cast<ColumnAttribute>()
  13.                    .Any(attr => attr.Name == column));
  14.  
  15.            // if no property matched - fall back to default type map
  16.            if (property == null)
  17.            {
  18.                property = fallback.GetMember(column)?.Property;
  19.            }
  20.  
  21.            return property;
  22.        });
  23.    };
  24.  
  25.     using var connection = new SqliteConnection("Data Source=:memory:");
  26.    
  27.     var result = await connection.QuerySingleAsync<QueryResult>("SELECT 1 AS 'Hello World', 2 AS 'HelloMars'");
  28.    
  29.     result.Dump();
  30. }
  31.  
  32. class QueryResult
  33. {
  34.     public int HelloMars { get; set; }
  35.    
  36.     [Column("Hello World")]
  37.     public int X { get; set; }  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement