Mapping an object with read-only properties using Dapper

106 views Asked by At

I am working to convert ADO.NET code to Dapper in C#. I am trying to map a class, DerivedEntity, which inherits from BaseEntity. BaseEntity has two properties, ID and GameKey which only have getters and no setters. To add more complexity, there is a property, ExampleProperty which is a custom type Example.

public class DerivedEntity: BaseEntity
{
    public DerivedEntity() { }
    public DerivedEntity(int id, int someKey) : base(id, someKey)
    {

    }
}

public class BaseEntity
{
    public Play() { }
    public Play(int id, int someKey)
        {
            ID = id;
            SomeKey = someKey;
        }
    public int ID { get; }
    public int SomeKey { get; }
    public Example ExampleProperty { get; set; }
}

The ADO.NET code was handling the ID and SomeKey properties like so:

while (await sqlreader.ReadAsync()) 
{
    DerivedEntity test = new DerivedEntity((int)sqlreader\["ID"\], (int)sqlreader\["SomeKey"\]);
    test.AnotherPropery = sqlreader\["AnotherProperty"\]; // more manual mapping 
}

My current code maps all of the properties except for ID and SomeKey, which are returned as 0:

results = (await sqlcon.QueryAsync<DerivedProperty, Example, DerivedProperty>(        
    sql: "my_stored_procedure",                     
    map: (result, example) => {                         
        result.ExampleProperty = new Example(result.GameKey, result.ID, play.PlayerID);                           
        return result;                     
    },                     
    param: parameters,                     
    splitOn: "ExampleProperty",                     
    commandType: CommandType.StoredProcedure,                     
    commandTimeout: 1000)).ToList();

I thought about instantiating the DerivedEntity object, but figured it would require manually mapping the rest of the properties. Is there any way to map the object automatically?

0

There are 0 answers