How to pass objects returned by the anonymous type. GetType () to the generic type

Source: Internet
Author: User
// How do I obtain an anonymous type and put it in // generic t ?? VaR anonymous = new {A = 0, B = 1}; type T = anonymous. getType (); // then var xx = dbcontext. database. sqlquery <t> ("SQL"); // tragedy var xx2 = dbcontext. database. sqlquery <dynamic> ("SQL"); // xx2 has a list, but all objects .. ~~~ The real items cannot be displayed. The profile and... SQL statements are used to submit and explain.

Solution of msdn

So we recorded it.

The reason for this problem is that there is no attribute definition required by Entity Framework on the dynamic type, and Entity Framework maps the attributes on the reflection type. To solve this problem, I used the emit technology to dynamically generate a type and dynamically write the Il code to generate attributes. The Code is as follows. The test passed on C #4.0.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.Entity;using System.Collections;using System.Reflection.Emit;using System.Reflection; namespace Demo{  public class Program  {    public static void Main(string[] args)    {      string connectionString = "Server=(local); Integrated Security=true; Database=master";      using (DbContext context = new DbContext(connectionString))      {        TypeBuilder builder = Program.CreateTypeBuilder("MyDynamicAssembly", "MyModule", "MyType");        Program.CreateAutoImplementedProperty(builder, "name", typeof(string));        Program.CreateAutoImplementedProperty(builder, "type", typeof(string));        Program.CreateAutoImplementedProperty(builder, "id", typeof(int));         Type resultType = builder.CreateType();         dynamic queryResult = context.Database.SqlQuery(resultType, "SELECT * FROM sys.sysobjects");         Console.WriteLine("{0,20} {1,4} {2,10}", "Name", "Type", "ID");        foreach (dynamic item in queryResult)        {          Console.WriteLine("{0,10} {1,4} {2,10}", item.name, item.type, item.id);        }      }       Console.ReadKey();    }     public static TypeBuilder CreateTypeBuilder(string assemblyName, string moduleName, string typeName)    {      TypeBuilder typeBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Run).DefineDynamicModule(moduleName).DefineType(typeName, TypeAttributes.Public);      typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);      return typeBuilder;    }     public 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, PropertyAttributes.HasDefault, propertyType, null);       // Property getter and setter attributes.      MethodAttributes propertyMethodAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;       // 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.Ldarg_0);      getterILCode.Emit(OpCodes.Ldfld, fieldBuilder);      getterILCode.Emit(OpCodes.Ret);       // 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.Ldarg_0);      setterILCode.Emit(OpCodes.Ldarg_1);      setterILCode.Emit(OpCodes.Stfld, fieldBuilder);      setterILCode.Emit(OpCodes.Ret);       propertyBuilder.SetGetMethod(getterMethod);      propertyBuilder.SetSetMethod(setterMethod);    }  }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.