I have a class User
with a nested class Bank
.
class User{
int Id;
string username;
Bank bank;
}
Class Bank{
int id;
string name;
}
I need to create an Insert function for User
. Is there a way in Dapper
to execute a query and binding the parameters from a nested a object ?
For such a scenario where not just a
User
object but aList<User>
might also need a db insertion, you can consider usingtable valued parameters
. For your question it would be:Use
IEnumerable<User>
andIEnumerable<Bank>
, even if it is just one objectMake the
TVP
with appropriate schema and same order ofcolumns
as inIEnumerable collection
for the stored procedure, else it will lead to errorYou can use
dynamic parameters
to bind the parameters, where forTVP
,IEnumerable
can be supplied using extension methodAsTableValuedParameters
in case you are usinganonymous type
parameters notdynamic parameters
, then use theObjectReader
fromFastMember
in Nuget to convertIEnuemrable<T>
toDatatable
, which is mandatory for TVP. Even custom code can be used forIEnuemrable<T>
toDatatable
conversion, in case few columns need to be omitted, following is the code snippet:You can write a custom mapper for Dapper using DapperExtensions:
https://github.com/tmsmith/Dapper-Extensions/wiki/Customized-mapping-for-a-class
Make sure you register the assembly containing the mapper: