mercredi 6 septembre 2017

Dynamic Func<> for Dapper query map

I'm attempting to dynamically generate and execute the sql for Dapper with the aim to simply pass in a type and the sql is generated and executed dynamically.

Example classes:

public class User
{
    [Key]
    public int UserId { get; set; }
    public Address Address { get; set; }
}
public class Address
{
    [Key]
    public int UserId { get; set; }
    public string PostCode { get; set; }
}

Will effectively run the following:

// sql: "SELECT User.UserId, Address.UserId, Address.PostCode FROM User LEFT JOIN Address ON Address.User = User.UserId"... // auto generated from 'User' type including join to 'Address';

connection.Query<User, Address, User>(sql, /*** map argument needs to be dynamic Func<> ***/);

So given these types User & Address which are only known at runtime, how can I generate the appropriate delegate Func<User, Address, User> to pass to the map argument?

Func<User, Address, User> map = (u, a) => {
    u.Address = a;
    return u;
}

The examples I have seen for creating a Func<> using reflection assume the types are known, in my case they aren't so the type arguments vary (Func<,> / Func<,,> / Func<,,,> etc).

Any help appreciated. I'll keep working through examples using expressions to see if anything sticks.





Aucun commentaire:

Enregistrer un commentaire