Home >Database >Mysql Tutorial >How to Extract Anonymous Type Results from SQL Queries Using Entity Framework?
Anonymous Type Result Extraction from SQL Queries in Entity Framework
In Entity Framework, the SqlQuery
To overcome this limitation and obtain anonymous type results, the solution lies in leveraging raw SQL directly. The provided method, DynamicListFromSql, allows developers to achieve this functionality.
public static IEnumerable<dynamic> DynamicListFromSql(this DbContext db, string Sql, Dictionary<string, object> Params) { using (var cmd = db.Database.Connection.CreateCommand()) { cmd.CommandText = Sql; if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); } foreach (KeyValuePair<string, object> p in Params) { DbParameter dbParameter = cmd.CreateParameter(); dbParameter.ParameterName = p.Key; dbParameter.Value = p.Value; cmd.Parameters.Add(dbParameter); } using (var dataReader = cmd.ExecuteReader()) { while (dataReader.Read()) { var row = new ExpandoObject() as IDictionary<string, object>; for (var fieldCount = 0; fieldCount < dataReader.FieldCount; fieldCount++) { row.Add(dataReader.GetName(fieldCount), dataReader[fieldCount]); } yield return row; } } } }
This method enables developers to execute SQL queries and retrieve results in the form of dynamic objects, which are stored as key-value pairs within an ExpandoObject instance.
To employ this method in your own code, simply call it as follows:
List<dynamic> results = DynamicListFromSql(myDb,"select * from table where a=@a and b=@b", new Dictionary<string, object> { { "a", true }, { "b", false } }).ToList();
By utilizing this approach, developers can obtain anonymous type results from SQL queries with ease, facilitating the retrieval of specific columns or the creation of custom data structures based on the query results.
The above is the detailed content of How to Extract Anonymous Type Results from SQL Queries Using Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!