. NET using SQL in EF, use dynamic Class!

Source: Internet
Author: User
Tags emit

. NET using SQL in EF, use dynamic Class!

Preface

Using the Entity Framework in. NET makes it quick and easy to combine LINQ with a series of additions and deletions to the database. But because EF executes based on the expression of the last generation of common SQL, it performs specific database operations. Based on my experience with EF, I can use EF's interface to quickly develop the operation of adding, deleting and changing. But for the operation of the query, it is best to use EF to invoke SQL to operate.

Problem Presentation

    After calling SQL for a data query in EF, you need to return a list of data of the specified type, which you need to specify at the time of invocation. We will encounter this problem: I just need to look up some simple data, such as query the number of data to meet a certain criteria, and so on, you must create a new type, increase the redundancy of the program.

Solution Solutions

    To implement a method that dynamically generates classes, you can insert property names and property types, and return a type that is available to EF for use.

Implement

    

 //the class is used to define an attribute node, including the name of the property and the type of the property. 
Public class PropertyItem { string name, type type) { thi S . Name = name; this . Type = type; public string Name {set ; get public type type {set ; get ;} }

     

//The class is provided with interfaces that dynamically generate types of.
Public classUsertypefactory { Public StaticType Getusertype (paramspropertyitem[] itemList) {TypeBuilder Builder=Createtypebuilder ("mydynamicassembly","MyModule","MyType"); foreach(varIteminchitemList) {Createautoimplementedproperty (builder, item. Name, item. Type); } Type Resulttype=Builder. CreateType (); returnResulttype; } Private StaticTypeBuilder Createtypebuilder (stringAssemblyName,stringModuleName,stringtypeName) {TypeBuilder TypeBuilder=AppDomain. CurrentDomain. DefineDynamicAssembly (NewAssemblyName (AssemblyName), Assemblybuilderaccess.run). DefineDynamicModule (ModuleName). DefineType (TypeName, typeattributes.public); Typebuilder.definedefaultconstructor (Methodattributes.public); returnTypeBuilder; } Private Static voidCreateautoimplementedproperty (TypeBuilder builder,stringPropertyName, Type PropertyType) { Const stringPrivatefieldprefix ="m_"; Const stringGetterprefix ="get_"; Const stringSetterprefix ="set_"; //define a field.FieldBuilder FieldBuilder =Builder. DefineField (string. Concat (Privatefieldprefix, PropertyName), PropertyType, fieldattributes.private); //Defining PropertiesPropertyBuilder PropertyBuilder =Builder. DefineProperty (PropertyName, System.Reflection.PropertyAttributes.HasDefault, PropertyType,NULL); //properties of getter and setter attributesMethodAttributes propertymethodattributes =Methodattributes.public| MethodAttributes.SpecialName |Methodattributes.hidebysig; //Defining Getter MethodsMethodBuilder Gettermethod =Builder. DefineMethod (string. Concat (Getterprefix, PropertyName), Propertymethodattributes, PropertyType, type.emptytypes); ILGenerator Getterilcode=Gettermethod.getilgenerator (); Getterilcode.emit (OPCODES.LDARG_0); Getterilcode.emit (OPCODES.LDFLD, FieldBuilder); Getterilcode.emit (Opcodes.ret); //Defining Setter MethodsMethodBuilder Settermethod =Builder. DefineMethod (string. Concat (Setterprefix, PropertyName), Propertymethodattributes,NULL,Newtype[] {propertyType}); 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); } }

Use

    

 ymsentities entities=new ymsentities();
Dynamicstudentdic= entities. Database.sqlquery (Usertypefactory.getusertype (NewPropertyItem ("ID",typeof(int)),NewPropertyItem ("Num",typeof(string))),"Select ID, Name as num from student");foreach(varUserCountinchstudentdic) {
//Business}

. NET using SQL in EF, use dynamic Class!

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.