Custom ormapping-relational tables converted to entity or entity collection objects

Source: Internet
Author: User

Overview

ormapping, Chinese translation is, the mapping of the relationship object, his role is to enable us to program, not too much attention to the persistence layer, just focus on the object, focus on the business. ormapping Mainly completes two functions: automatic generation of SQL statements and DataTable to Objects.

Features and Reflections

Attributes are used to describe metadata, which is the code after the source code has been compiled. Reflection is the runtime that gets all the information about an object or class, and with this information, we can create classes to get attribute information and so on

How a relational table is converted to an entity or Entity collection Object

There are several ways to implement a relational table conversion to an entity or Entity collection object, and here are two extremes.

Relational tables are converted to entity collections, and the bad effect is that, for each entity collection type, we create a class that implements the transformation of the corresponding relationship and entity, and the good effect is to create a class that implements the conversion of a DataTable of all entity collection types, no longer provides code for bad ways, For a good way, provide the following code. We can look at the implementation inside.

Custom attribute Classes

Using system;using system.collections.generic;using system.linq;using system.text;namespace collection. Collection. custom attribute {    [ AttributeUsage (Attributetargets.property,allowmultiple=true,inherited=false)] public    class Ormappingfieldattribute:attribute    {        private string _strfieldname;        Public Ormappingfieldattribute (String _strfieldname)        {            this._strfieldname = _strfieldname;        }        public string strFieldName         {            get {return _strfieldname;}        }    }

Entity class

Using system;using system.collections.generic;using system.linq;using system.text;using collection. collection. Custom attributes; namespace Tabletocollection. Entity {    [ormappingtable ("T_person")] public    class person    {        [Ormappingfield ("id")] Public        string Strid {get; set;}        [Ormappingfield ("name")]        public string StrName {get; set;}        [Ormappingfield ("Age")]        public int IntAge {get; set;}}    }

Relational Object Transformation Classes

The Using system;using system.collections.generic;using system.linq;using system.text;using collection. Database access; A collection of flexible collections. ; using System.reflection;using system.data;using collection. collection. Custom attributes; namespace collection.        ormapping.ormapping{public class ormapping<t> where T:new () {private DataTable dt;        Public ormapping () {dt = new DataTable ();            } public void Getdatatable () {Persondll Persondll = new Persondll ();        DT = Persondll.query (); } public void Datarowtotobject (T Tobject,datarow DR) {//Get the entity type types type = Tobje Ct.            GetType (); Gets all public properties of type T propertyinfo[] Allpropertyinfo = type.            GetProperties ();                foreach (PropertyInfo item in Allpropertyinfo) {//Returns all attributes of the custom Ormappingfieldattribute of the property object[] Propertycustomattributes = Item.                GetCustomAttributes (typeof (Ormappingfieldattribute), false); foreach (OrmappiNgfieldattribute attribute in propertycustomattributes) {if (dt. Columns.contains (Attribute.strfieldname)) {Object tobjectpropertyvalue = Dr[att                        Ribute.strfieldname];                        if (Tobjectpropertyvalue = = DBNull.Value) {continue; } #region Type Conversion if (item. Propertytype.equals (typeof (String))) {Tobjectpropertyvalue = Dr[attribu Te.strfieldname].                        ToString (); } else if (item. Propertytype.equals (typeof (int))) {Tobjectpropertyvalue = Convert.toint                        (Dr[attribute.strfieldname]); } else if (item. Propertytype.equals (typeof (Decimal))) {TobjectpropertyvalUE = Convert.todecimal (Dr[attribute.strfieldname]); } else if (item. Propertytype.equals (typeof (DateTime))) {Tobjectpropertyvalue = Convert.                        ToDateTime (Dr[attribute.strfieldname]); } else if (item. Propertytype.equals (typeof (Double))) {Tobjectpropertyvalue = Convert.to                        Double (Dr[attribute.strfieldname]); } else if (item. Propertytype.equals (typeof (BOOL))) {Tobjectpropertyvalue = Convert.tobo                        Olean (Dr[attribute.strfieldname]); }///Use reflection to automatically assign value to the corresponding public property of obj item.                        SetValue (TObject, tobjectpropertyvalue, NULL); #endregion}}}} public void DataviewtocollectioN (basecollection<t> tcollection) {getdatatable (); for (int i = 0; i < dt. Rows.Count;                               i++) {T tobject = new T (); Datarowtotobject (tobject, dt.                Rows[i]);     Tcollection.add (TObject); }                    }          }}
The core code in the main function

ormapping<person> ormapping = new ormapping<person> (); Personbasecollection personbasecollection = new Personbasecollection (); Ormapping.dataviewtocollection ( Personbasecollection);

the approximate idea of realization

The DataTable is converted to an entity collection object, to accomplish this function, each row in the DataTable must be assigned the value of each cell in the Entity collection object to the specific properties of the specific object, for the above-mentioned bad effect, we can be very simple implementation, but, That's not the way it works (not exactly).

How does the good effect of the above be realized? The implementation of the knowledge for the characteristics and reflection, through the use of custom properties on the entity class, we can in the program run, through reflection, to obtain all the information of the corresponding object, by getting the custom attributes, we can get, objects in the object and the corresponding table field object relationship, through reflection, We can get the type of the object property and then make the appropriate conversion.

Custom attribute classes (which implement the corresponding relationship between the attribute in the class and the field name of the table), apply custom attributes on the entity class, get all the information of the entity object by reflection, derive the attribute information from the definition, and convert the fields and properties of the table and object to each other.

Summary

Custom romapping also poor automatic generation of SQL This function, for the realization of this piece, I am not very clear, I believe there will be clear that day, in addition, the Summary of LINQ also owes you some things, because this piece of the demo has not been achieved, the latter will be the corresponding content.

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.