Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing dynamic parameters with ExpandoObject

I have some function whose prototype looks kind of like this: public void doThings(string sql, dynamic dParams);

It does some kind of SQL querying with those parameters. I didn't write it but I have to use it. It works fine when I do something like this:

doThings("select * from SomeTable where myval1=@v1 and myval2=@v2",
        new
        {
            v1 = new Dapper.DbString()
            {
                Value = "yay",
                IsAnsi = true,
                Length = 50
            },
            v2 = new Dapper.DbString()
            {
                Value = "really",
                IsAnsi = true,
                Length = 32
            }
        });

But not when I first put the dynamic params into an ExpandoObject:

dynamic dynParams = new ExpandoObject();
dynParams.v1 = new Dapper.DbString()
    {
        Value = "yay",
        IsAnsi = true,
        Length = 50
    }
doThings("query here", dynParams);  

The query then returns no results. I don't want to call doThings() and write that new block ten times for ten different scenarios where I might want to query for myval2 or myval3 and so on. Is there some special way I should be passing the ExpandoObject, or some other way I should be doing this in general?

like image 956
idlackage Avatar asked Sep 24 '13 16:09

idlackage


People also ask

Is ExpandoObject dynamic?

The ExpandoObject class is an implementation of the dynamic object concept that enables getting, setting, and invoking members.

When to use ExpandoObject?

Use ExpandoObject to create an object that you can add properties, methods, and events to and be able to data bind to in a user interface. ExpandoObject allows you to write code that is more readable than typical reflection code with GetProperty(“Field”) syntax.

How do I know if I have ExpandoObject property?

For ExpandoObject, you can simply check whether the property is defined as a key in the underlying dictionary. For other implementations, it might be challenging and sometimes the only way is to work with exceptions.


1 Answers

Dapper doesn't support Expandos by default, but you can pass the expando to the constructor of a Dictionary<string,object> and then pass that as the dynamic argument.

like image 162
Michael B Avatar answered Sep 28 '22 12:09

Michael B