How to create an anonymous object with property names determined dynamically?

后端 未结 3 520
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 22:56

Given an array of values, I would like to create an anonymous object with properties based on these values. The property names would be simply \"pN\" where N

3条回答
  •  暖寄归人
    2021-02-01 23:06

    You are misusing Dapper, you should never need to do this, instead either implement IDynamicParameters or use the specific extremely flexible DynamicParameters class.

    In particular:

    string sql = "select * from Account where Id = @id and username = @name";
    var values = new DynamicParameters();
    values.Add("id", 1);
    values.Add("name", "bob");
    var accounts = SqlMapper.Query(connection, sql, values);
    

    DynamicParameters can take in an anonymous class in the constructor. You can concat DynamicParameters using the AddDynamicParams method.

    Further more, there is no strict dependency on anon-types. Dapper will allow for concrete types as params eg:

    class Stuff
    {
       public int Thing { get; set; }
    }
    
    ...
    
    cnn.Execute("select @Thing", new Stuff{Thing = 1});
    

    Kevin had a similar question: Looking for a fast and easy way to coalesce all properties on a POCO - DynamicParameters works perfectly here as well without any need for magic hoop jumping.

提交回复
热议问题