An ORM implementation (with source code), and An orm implementation with source code

Source: Internet
Author: User

An ORM implementation (with source code), and An orm implementation with source code
1 Preface

After a period of writing, I finally came up with a stable version, during which I considered a variety of solutions and secretly learned the works of the great gods in the garden.

There are already many ORM frameworks. Why should we implement one by ourselves? My reason is that you can add specific code to the orm when encountering special requirements. For example, perform basic data verification based on the field length and void of the database, and solve the synchronization problem during data modification in the ORM...

This article focuses on how to implement ORM. For other articles, refer to the following:

Use T4 Template to generate code: refer to this article to learn how this ORM generates entity-layer code based on the database. With this foundation, you can understand all the T4 templates in this text.

DBHelper (support for transactions and database changes): refer to this article to learn how this ORM accesses the database, how to support transactions, paging, and multiple databases.

2. Implementation Method

This article focuses on the blue ORM section.

Model: defines the base class of an object. Each table generates the corresponding entity and inherits this class;

ModelMapping: defines the structure information of a table, including the table name, primary key, and field type. Each table generates one;

ModelMappingReflector: when the program runs for the first time, it reflects all the ModelMapping subclasses and adds them to a dictionary set;

DataAccess <T>: When this type is used, an SQL statement is automatically generated to access the database (Add, Update, Delete) based on the schema information of the object and the object ); or add the value of the database to the object (GetModel, GetList ). This type of work helps us with CRUD. We no longer need to write the basic addition, deletion, modification, and query operations for each table, but still need to write queries for complex services. Each table generates an empty dao class and inherits this class.

The core class of this ORM is DataAccess <T>. The following uses Add as an example:

Add operation code

public int Add(T model){    if (model == null)    {        throw new ArgumentNullException();    }    StringBuilder cmdText = new StringBuilder();    cmdText.Append("INSERT INTO ").Append(modelMapping.TableName).Append(" (");    cmdText.Append(string.Join(",", model.ColumnValues.Keys.ToArray()));    cmdText.Append(") VALUES (@");    cmdText.Append(string.Join(", @", model.ColumnValues.Keys.ToArray()));    cmdText.Append(")");    List<DbParameter> dbParms = new List<DbParameter>();    foreach (var pair in model.ColumnValues)     {        dbParms.Add(DBHelper.CreateInDbParameter(string.Format("@{0}",pair.Key), modelMapping.ColumnDict[pair.Key].DbDataBype, pair.Value));    }    return this.ExecuteNonQuery(CommandType.Text, cmdText.ToString(), dbParms.ToArray());}

 

When we write such code, the User model = new User (); model. UserName actually adds data to the ColumnValues set in the Model. To generate an insert SQL (INSERT INTO tablename (column1, colum2) VALUES (@ column1, @ column2) and add INSERT parameters, we need the table name, column name, column value and column type. The column name and column value exist in the ColumnValues set in the Model. The column type and table name can be obtained in ModelMapping.

3 Example static void Main (string [] args) {TestORM (); TestPaging (); Console. readLine ();} static void TestORM () {UserDao dao = new UserDao (); try {dao. beginTransaction (); // add model User mUser1 = new User (); mUser1.ID = "1"; mUser1.UserName = "Mike1"; mUser1.UserPwd = "1234"; mUser1.CreateBy = "System "; mUser1.CreateDate = DateTime. now; dao. add (mUser1); Console. writeLine ("Create Model Successfully. "); s Tring into text = "SELECT * FROM TUser where id = '1' order by id;"; List <User> list0 = dao. getListBySQL (plain text); foreach (User model in list0) {Console. writeLine (model. userName);} Console. writeLine ("Get List Successfully. "); // nested transaction UserDao dao2 = new UserDao (); try {dao2.BeginTransaction (); // update model User mUser2 = new User (); mUser2.ID =" 1 "; mUser2.UserName = "Mike. jiang "; mUser2.UserPwd = Null; mUser2.CreateDate = null; dao. update (mUser2); Console. writeLine ("Update Model Successfully. "); User mUser3 = dao. getModel ("1"); if (mUser3! = Null) Console. writeLine (mUser3.UserName); Console. writeLine ("Get Model Successfully. "); dao2.CommitTransaction ();} catch {dao2.RollbackTransaction ();} dao. delete ("1"); Console. writeLine ("Delete Model Successfully. "); dao. commitTransaction ();} catch (Exception ex) {Console. writeLine (ex. message); dao. rollbackTransaction () ;}} static void TestPaging () {UserDao dao = new UserDao (); // add 100 user for (int I = 1; I <= 100; I ++) {User mUser1 = new User (); mUser1.ID = I. toString (); mUser1.UserName = "Mike" + I. toString (); mUser1.UserPwd = "1234"; mUser1.CreateBy = "System"; mUser1.CreateDate = DateTime. now; dao. add (mUser1);} string plain text = string. format ("SELECT * FROM TUser"); DataTable table = DBHelper. executePagingDataTable (CommandType. text, plain Text, 1, 10, "order by id"); foreach (DataRow row in table. rows) {Console. writeLine (row ["ID"]);} Console. writeLine ("Get Datatabe paging successfuly. "); List <User> list = dao. getListPaging (plain text, 2, 10, "order by id"); foreach (User m in list) {Console. writeLine (m. ID);} Console. writeLine ("Get Model list paging successfully. "); plain text =" delete from TUser "; dao. executeNonQuery (CommandType. text, plain Text );}View Code

 

 

4. Summary

This version of the ORM example is not carefully written, because it is not considered to be useful. However, this ORM code is a simple version that I think only has the core functions and several classes of the ORM. Anyone with the c # foundation can understand it, for more information, see. In the future, you will add Pager-related content, data synchronization, data verification functions, and the ability to automatically generate object based on SQL.

All source code: BaseProject.7z


What do you use for ORM code generators?

Soft, or write a small tool by yourself

A simple personal webpage with the source code to submit the static

For your topic, find a simple personal webpage with the source code to submit the static job,
Contact us to provide your questions and email,
If you have more requirements, let us know,
May help you,
Please use BaiduHi to leave a message for me,
This reply is valid for all requests and visitors,
ES: \ 7A294A3895BAABEE0EDFBD11B27B34C6

Related Article

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.