简体   繁体   中英

Project dynamic Dapper results excluding some properties

Given a dynamic Dapper query such as:

var results = connection.Query<dynamic>("SELECT ....");

I want to remove a couple of the returned columns/properties from the results. The trick is I want to do this without knowing/caring the names of the properties I want to keep, otherwise I would simply project the results into a new anonymous type.

I attempted to loop through the results and cast each to an IDictionary<string, object> so that I could simply remove the key/value pair holding the data. Unfortunately, for whatever reason, the underlying internal FastExpando object doesn't implement the Remove method. The source code for FastExpando shows:

bool IDictionary<string, object>.Remove(string key)
{
    throw new NotImplementedException();
}

How can I implement this? To be clear I basically want:

var filteredResults = from r in results
                      select new { // All properties except a couple of well-known ones }

What if you iterate the FastExpandoObject and return a filtered ExpandoObject ?

 var filteredResults = dynamicResult.Select<dynamic, dynamic>(x =>
                    {
                        var filteredRow = new ExpandoObject() as IDictionary<string, Object>;
                        var props = x as IDictionary<string, object>;
                        foreach (var prop in props)
                        {
                            if (!filter.Contains(prop.Key))
                                filteredRow.Add(prop);
                        }
                        return filteredRow;
                    });

There was no reason that FastExpandoObject didn't implement those methods, other than: it hadn't needed to. I have now filled in all the missing / NotImplementedException methods. I haven't yet deployed to NuGet, but the code on github/google-code has been updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM