Anonymous type result from sql query execution entity framework

anonymous-types c# entity-framework sql


Entity Framework 5.0 and the code-first approach Framework 4.0 are what I'm using. I now understand how to run raw SQL in entity framework by doing the following.

var students = Context.Database.SqlQuery<Student>("select * from student").ToList();

It's functioning well, however what I need is results that are returned anonymously. For instance, I only want certain columns from the student table, such as the ones below.

var students = Context.Database.SqlQuery<Student>("select FirstName from student").ToList();

It is not functioning. It makes an exception.

The data reader is incompatible with the specified 'MyApp.DataContext.Student'. A member of the type, 'StudentId', does not have a corresponding column in the data reader with the same name.

I have thus tried.dynamic type

var students = Context.Database.SqlQuery<dynamic>("select FirstName from student").ToList();

It returns an empty object, hence it is likewise broken. There is no data in it.

Is there a method to receive results from a dynamic SQL query that are anonymous type?

11/5/2014 5:48:56 AM

Accepted Answer

The final answer, which satisfied me, is provided here.

public static System.Collections.IEnumerable DynamicSqlQuery(this Database database, string sql, params object[] parameters)
            TypeBuilder builder = createTypeBuilder(
                    "MyDynamicAssembly", "MyDynamicModule", "MyDynamicType");

            using (System.Data.IDbCommand command = database.Connection.CreateCommand())
                    command.CommandText = sql;
                    command.CommandTimeout = command.Connection.ConnectionTimeout;
                    foreach (var param in parameters)

                    using (System.Data.IDataReader reader = command.ExecuteReader())
                        var schema = reader.GetSchemaTable();

                        foreach (System.Data.DataRow row in schema.Rows)
                            string name = (string)row["ColumnName"];
                            //var a=row.ItemArray.Select(d=>d.)
                            Type type = (Type)row["DataType"];
                            if(type!=typeof(string) && (bool)row.ItemArray[schema.Columns.IndexOf("AllowDbNull")])
                                type = typeof(Nullable<>).MakeGenericType(type);
                            createAutoImplementedProperty(builder, name, type);

            Type resultType = builder.CreateType();

            return database.SqlQuery(resultType, sql, parameters);

        private static TypeBuilder createTypeBuilder(
            string assemblyName, string moduleName, string typeName)
            TypeBuilder typeBuilder = AppDomain
                .DefineDynamicAssembly(new AssemblyName(assemblyName),
                .DefineType(typeName, TypeAttributes.Public);
            return typeBuilder;

        private static void createAutoImplementedProperty(
            TypeBuilder builder, string propertyName, Type propertyType)
            const string PrivateFieldPrefix = "m_";
            const string GetterPrefix = "get_";
            const string SetterPrefix = "set_";

            // Generate the field.
            FieldBuilder fieldBuilder = builder.DefineField(
                string.Concat(PrivateFieldPrefix, propertyName),
                              propertyType, FieldAttributes.Private);

            // Generate the property
            PropertyBuilder propertyBuilder = builder.DefineProperty(
                propertyName, System.Reflection.PropertyAttributes.HasDefault, propertyType, null);

            // Property getter and setter attributes.
            MethodAttributes propertyMethodAttributes =
                MethodAttributes.Public | MethodAttributes.SpecialName |

            // Define the getter method.
            MethodBuilder getterMethod = builder.DefineMethod(
                string.Concat(GetterPrefix, propertyName),
                propertyMethodAttributes, propertyType, Type.EmptyTypes);

            // Emit the IL code.
            // ldarg.0
            // ldfld,_field
            // ret
            ILGenerator getterILCode = getterMethod.GetILGenerator();
            getterILCode.Emit(OpCodes.Ldfld, fieldBuilder);

            // Define the setter method.
            MethodBuilder setterMethod = builder.DefineMethod(
                string.Concat(SetterPrefix, propertyName),
                propertyMethodAttributes, null, new Type[] { propertyType });

            // Emit the IL code.
            // ldarg.0
            // ldarg.1
            // stfld,_field
            // ret
            ILGenerator setterILCode = setterMethod.GetILGenerator();
            setterILCode.Emit(OpCodes.Stfld, fieldBuilder);

8/5/2017 3:57:14 AM

Popular Answer

The entity framework SqlQuery<T> will only function for objects with known types, thus you must use raw SQL for that.

Here is the approach I take:

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;

        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;

You can refer to 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();

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow