question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Execute a query and map it to a list of dynamic objects

See original GitHub issue

please extend DbContext.Database.SqlQuery to support dynamic type for map query to a list of dynamic objects. for example:

var results = DbContext.Database.SqlQuery<dynamic>("SELECT * FROM Kids");
var id = result.First().Id;
var name = result.First().Name;
var age = result.First().Age ?? 0; // null support
foreach (var item in results)
{
     Console.WriteLine("{0}:{1}", item.Name, item.Age);
}

Issue Analytics

  • State:open
  • Created 8 years ago
  • Reactions:25
  • Comments:12 (1 by maintainers)

github_iconTop GitHub Comments

35reactions
ChristineBoersencommented, Jan 21, 2017

**NOTE this was written against pre RTM version of .Net core and may need to be modified to work with 1.0 RTM and newer versions of the framework

Attached is some code that provides this functionality with the existing framework. Let me know if this helps any.

    public static IEnumerable<dynamic> CollectionFromSql(this DbContext dbContext, string Sql, Dictionary<string, object> Parameters)
    {
        using (var cmd = dbContext.Database.GetDbConnection().CreateCommand())
        {
            cmd.CommandText = Sql;
            if (cmd.Connection.State != ConnectionState.Open)
                cmd.Connection.Open();

            foreach (KeyValuePair<string, object> param in Parameters)
            {
                DbParameter dbParameter = cmd.CreateParameter();
                dbParameter.ParameterName = param.Key;
                dbParameter.Value = param.Value;
                cmd.Parameters.Add(dbParameter);
            }

            //var retObject = new List<dynamic>();
            using (var dataReader = cmd.ExecuteReader())
            {

                while (dataReader.Read())
                {
                    var dataRow = GetDataRow(dataReader);
                    yield return dataRow ;

                }
            }


        }
    }

    private static dynamic GetDataRow(DbDataReader dataReader)
    {
        var dataRow = new ExpandoObject() as IDictionary<string, object>;
        for (var fieldCount = 0; fieldCount < dataReader.FieldCount; fieldCount++)
            dataRow.Add(dataReader.GetName(fieldCount), dataReader[fieldCount]);
        return dataRow;
    }

Usage:

List<dynamic> MyList = MyDbContext.CollectionFromSql("SELECT * FROM \"User\" WHERE UserID = @UserID",
            new Dictionary<string, object> { { "@UserID", 1 } }).ToList();

You will notice I used a Dictionay<string, object> since there are still some issues with passing a DbParameter currently - Support passing DbParameter instances to raw SQL APIs #3115

2reactions
fixkocommented, Feb 23, 2017

In ChristineBoersen code Just replace dbContext.Database.GetDbConnection().CreateCommand() with dbContext.Database.Connection.CreateCommand()

Read more comments on GitHub >

github_iconTop Results From Across the Web

Dynamic query into a map
You have to use Database.query. List<String> contactIdSet = new List<String>{'003123456789632145'}; String whereText = 'AccountId!=null'; String ...
Read more >
Spring JDBC Dynamic Query into Map of objects
I have to dynamically execute queries which will come from database.The query has dynamic fields,which needs to be converted into map as key ......
Read more >
Walkthrough: Creating and Using Dynamic Objects in C# | ...
Learn how to create and use dynamic objects in this walkthrough. Create a custom dynamic object and a project that uses an 'IronPython' ......
Read more >
17.11.3 Creating Dynamic Lists
A dynamic list enables you to create a List component based on items from a SQL query or a PL/SQL function returning a...
Read more >
Learn How to Map Result to Dynamic Object - Dapper Tutorial
The QueryFirst method can execute a query and map the first result to a dynamic list. The following example shows how to map...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found