Binding a complex model to Dapper DynamicParameters

42 Views Asked by At

I have a data model that is potentially two layers deep as shown below:

public class UserAccount {
    [JsonPropertyName("INTERNAL_USER_NUMBER")]
    public int? InternalUserNumber {get; set;}
    
    [JsonPropertyName("AVATAR")]
    public string? Avatar {get; set;}

    public List<Team>? Teams {get; set;}
}

public class Team
{
    public int? Id {get; set;}
    public string? Description {get; set;}
}

Its unclear how I should be sending a complex object like this our database. I have the following: Nested objects in Dapper Query parameter but this only addresses objects created as parameters directly but does not touch on the fact that objects can be directly binded to the parameters as referred to in this tutorial: https://www.learndapper.com/parameters#dapper-dynamic-parameters. Unfortunately the example in this site only shows a simple object and not one with nested objects. So can this be done?

My current implementation attempting this is :

public UserAccount Read(UserAccount userAccount)
    {
        using(var connection = _context.CreateConnection())
        {
                var parameters = new DynamicParameters(userAccount);
                string json = connection.QuerySingle<string>("select dbo.A2Q_0169W_UsersAccountsTBLInfo_JSON(@EmailAddress)", new DynamicParameters(userAccount));
                return JsonSerializer.Deserialize<UserAccount>(json)!;
        }
    }

If this cannot be done what is the best way to handle this dynamically? Should I serialize to JSON and send to the database and for MS SQL server utilize FOR JSON

1

There are 1 best solutions below

1
David Browne - Microsoft On

Dapper isn't an Object/Relational mapper, so doesn't really help here.

Normally you would use three tables to store this data:

UserAccount, Team, and a "bridge table" called something like TeamMembership.

You can use Entity Framework to generate the database, even if you don't use it at runtime.