C # Basic series: Implement Your own ORM (reflection and attribute in ORM)

Source: Internet
Author: User

Application of Reflection and attribute in ORM

First, reflection
What is reflection?
Simply put, reflection is a way of dynamically acquiring object information at run time, such as knowing what properties, methods, delegates, and so on.
What's the use of reflection?
Reflection not only allows you to get information about objects while running, but also provides the ability to dynamically invoke object methods at run time and to dynamically set, get properties, and so on.
What's the use of reflection in an ORM?
The ORM implementation I'm discussing here is a description of the mapping rules in a custom attribute way. However, we do not know which object needs to correspond to which table, and these objects are independent of our ORM framework, so we can only define the mapping rules through custom attribute, and then use reflection to dynamically obtain these mapping rules.
Implementation of Reflection:
Let's talk about a simple way to get the property value of an object, assuming we have the class person, which has 3 properties name, Age,sex. We can dynamically get the values of these three properties of the person's object by means of reflection.

 Public classperson{Private string_name; Private int_age; Private string_sex;  Public stringName {Get{return  This. _name;} Set{ This. _name =value;} }     Public intAge {Get{return  This. _age;} Set{ This. _age =value;} }     Public stringSex {Get{return  This. _sex;} Set{ This. _sex =value;} }}

The test code is as follows:

Static classprogram{[STAThread]Static voidMain () { person person=NewPerson (); Person. Name="Snoopy"; Person. Age=5; Person. Sex="male"; Propertyinfo[] Infos=Person . GetType ().        GetProperties (); Console.WriteLine ("Print Properties"); foreach(PropertyInfo Infoinchinfos) {            //Get Properties and printConsole.WriteLine (Info. Name +":"+ info. GetValue (Person,NULL)); } Console.WriteLine ("Set person.name = Hellokitty"); //setting properties, setting the Name property        foreach(PropertyInfo Infoinchinfos) {            if(info.) Name = ="Name") {info. SetValue (person,"Hellokitty",NULL); }} Console.WriteLine ("Print Properties"); foreach(PropertyInfo Infoinchinfos) {            //Get Properties and printConsole.WriteLine (Info. Name +":"+ info. GetValue (Person,NULL));    } console.read (); }}

It shows how to get and set object properties dynamically by means of reflection. But what does this have to do with ORM and attribute? This is what we're going to do with this part of the next.


Second, the use of attribute:
Attribute Chinese translation, although also known as the "attribute", but she and the object of the property is actually a completely different two concept. She is a class that describes objects or object properties, methods, delegates, and so on at run time, and is used to describe your code at run time or to affect the behavior of your program at run time.
In fact, we often see attribute in C # programming, but we are not paying attention. For example, "[STAThread]" before the main function is actually a attribute. The whole journey is [STAThreadAttribute]. Also specify the class serializable [Serializable] and so on. Are you familiar with it? But the usual estimate is not used, so no attention.

Since Attribute is a class, her definition method and class are no different, the only difference is that the custom Attribute class must inherit from System.Attribute.
Let's briefly define a attribute that describes the database field information, in which we use a more omitted approach, providing only "field name", "Field type":

 Public classdatafieldattribute:attribute{Private string_fieldname; Private string_fieldtype;  PublicDatafieldattribute (stringFieldNamestringFieldType) {         This. _fieldname =fieldname;  This. _fieldtype =FieldType; }     Public stringFieldName {Get{return  This. _fieldname;} Set{ This. _fieldname =value;} }     Public stringFieldType {Get{return  This. _fieldtype;} Set{ This. _fieldtype =value;} }}

Well, we have our own attribute that describes the database fields, so we'll now apply them to the actual classes. Let's continue with the person class above, using the following method:

 Public classperson{Private string_name; Private int_age; Private string_sex; [Datafieldattribute ("name","nvarchar")]     Public stringName {Get{return  This. _name;} Set{ This. _name =value;} } [Datafieldattribute (" Age","int")]     Public intAge {Get{return  This. _age;} Set{ This. _age =value;} } [Datafieldattribute ("Sex","nvarchar")]     Public stringSex {Get{return  This. _sex;} Set{ This. _sex =value;} }}

By customizing attribute, we define the one by one correspondence between class properties and database fields, and we have added a attribute description of the name, age, and sex properties of the person class, specifying their corresponding field names and types. Where Person.name corresponds to field name, field type nvarchar ....

Third, the combined use of reflection and attribute.
From the above description, we understand the reflection, understand the attribute, and understand the definition of the ORM mapping rule. But the friends who just contacted are still confused, how do we dynamically acquire these mapping rules? Listen to batting practice slowly.
This requires the use of reflection:
In the following example, we have increased the datafieldattribute description of name,age and sex in person, which is actually an increase in the mapping rules for O (object)/R (relational database), and we can get this mapping rule dynamically by means of reflection:

Static classprogram{[STAThread]Static voidMain () { person person=NewPerson (); Person. Name="Snoopy"; Person. Age=5; Person. Sex="male"; Propertyinfo[] Infos=Person . GetType ().        GetProperties (); Object[] Objdatafieldattribute =NULL; foreach(PropertyInfo Infoinchinfos) {Objdatafieldattribute= info. GetCustomAttributes (typeof(Datafieldattribute),false); if(Objdatafieldattribute! =NULL{Console.WriteLine (info). Name+"Database fields:"+ ((datafieldattribute) objdatafieldattribute[0]).            FieldName); }        }    }}

Haha, do you really want to do it? Of course, if you start at this point, then I'm glad to say that my description is clear (note: This is not valid for the known Daniel). It also means that you have the ability to do it. Because the next task is how to dynamically get the mapping rules from the object, dynamically construct the Insert,update,delete and so on.

Iv. Summary of this chapter
In this chapter, I have described in more detail the concepts and applications of reflection, custom attribute, and how to dynamically acquire the mapping rules for O/R mapping at run time. Of course, my code here is just an example, and to really implement an ORM, there are a lot of things we need to consider, such as:
1. Which database table does the person correspond to?
2. What does PK and FK (if any) in person mean?
......
These questions will be explained in my next article.

Related connections:

C # Basic series: Implementing Your Own ORM (ORM's basic concept)

C # Basic series: Implement your own ORM (build my own ORM)

C # Basic series: Implementing Your Own ORM (miniorm test code)

Source code Download

C # Basic series: Developing Your own Form designer (PropertyGrid display Chinese property names)

C # Basic series: Implement Your own ORM (reflection and attribute in ORM)

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.