Using Dapper for binding using a strongly typed model with additional dynamic properties

We hope to move on to using Dapper to ensure that object relationships are aligned with our business models.

Along with these data models, we often encounter custom fields (unknown at runtime) that are created by users and displayed as part of the returned result set:

Id Title c_MyCustomField1 c_MyCustomField2 

Currently, all of these fields are returned and processed using a reader. We would like to move all this to Dapper , but we are struggling to figure out how to mix a strongly typed object mixed with dynamic custom fields.

We see our options as follows:

  • Get each result from dapper as dynamic and make your own binding.
  • Get Dapper to bind to a strongly typed model and make a separate call to add custom fields.
  • Expand Dapper to get in the middle, add our specific user case to link both known and dynamic fields.

1 seems counterproductive, and we might take a performance hit, so you should introduce Dapper first. 2 , we really cannot do this, because it will require a significant change in the data provider. 3 I know that I do not belong to the source of Dapper.

I think the holy grail will end with this model:

 class Model { int Id {get; set;} string Title {get; set;} IList<CustomField> CustomFields {get; set;} } class CustomField : dynamic { string Name {get; set;} object Value {get; set;} } 

Can this be done with Dapper?

As always, any suggestions were highly appreciated.

+4
source share
1 answer

Currently, this cannot be modeled purely. you can do something using a non-generic API and then manually apply the bindings. Or just wrap the dynamics:

 class Model { private dynamic obj; public int Id { get { return obj.Id; } set { obj.Id = value; } } public string Title { get { return obj.Title; } set { obj.Title = value; } } public object this[string key] { get { return ((IDictionary<string,object>)obj)[key]; } set { ((IDictionary<string,object>)obj)[key] = value; } } } 

You can get dynamic / IDictionary<string,object> using Query without specifying a common parameter.

+3
source

All Articles