What is the ORM framework __orm

Source: Internet
Author: User
Tags getdate
what is an ORM framework

Object-relational mapping, the current database is relational database ORM is mainly to map the relational data in the database to the object in the program.

The common ORM Framework is currently concentrated
1 Nhibernate
Reason: Use more, the data is also more easy to find.
2 Castle ActiveRecord
Reason: It's better than nhibernate to configure an object's XML file
3 EntityFramework
Reason: Microsoft's stuff (really, kinda don't want to use)
4 mybaits.net
Reason: I have a few Java friends said they do not need to hibernate now are using Mybaits.

5 Dapper ORM

If you like native SQL statements and you like the simplicity of ORM, you'll love the dapper rom. Click to download
Advantages of Dapper:
1,dapper is a lightweight ORM class. Code on a SqlMapper.cs file, compiled on a very small DLL for 40K.
2,dapper soon. The speed of the dapper is close to the IDataReader, and the data taken from the list exceeds the DataTable.
What database the 3,dapper supports. Dapper supports a series of databases such as mysql,sqllite,mssql2000,mssql2005,oracle, and of course, if you know the rationale, you can make IT support MONGO DB
4,dapper's R supports multiple-table parallel objects. Support a pair of many pairs of relationships. And not invasive, want to use it, do not want to use it. No XML no attributes. Code how to write it before and how it is written.
The 5,dapper principle uses emit to reflect IDataReader sequence queues to quickly obtain and produce objects. The performance is really high.
6,dapper supports net2.0,3.0,3.5,4.0. "If you want to use under the Net2.0, you can go to the Internet to find out how to configure the Net2.0 to run Net3.5." 】
7,dapper syntax is very simple. And no need to accommodate the design of the database.

The following is an example of how dapper can be used for efficient development, and the following are examples of Net3.5 operations under Net4.0, where most functions have a default value and the parameters are simple.

Tables in the database:
CREATE table Columncat
(
Id INT IDENTITY (1,1) not NULL PRIMARY KEY,
NAME NVARCHAR null,< C4/>modifiedon smalldatetime NULL DEFAULT (GETDATE ()),
parentid int
)

CREATE TABLE Column
(
Id int IDENTITY (1,1) NOT null PRIMARY KEY,
NAME NVARCHAR (+) NULL,
modifieddate smalldatetime null DEFAULT (GETDATE ( )),
columncatid INT null
)

Commonly used tables, categories, and content tables, categories can have subordinate categories. The following operations are essentially operations on both tables.

Connect the database string.
Private ReadOnly String SqlConnection =
                 "Data source=renfb;initial catalog=test; User Id=sa; Password=sa; ";
Public readonly String mysqlconnectionstring =
                 @ "server=127.0.0.1;database=test;uid=renfb;pwd=123456; charset= ' GBK ';

Gets the connection database object for SQL Server. SqlConnection public
SqlConnection OpenConnection ()
{
    SqlConnection connection = new SqlConnection ( SqlConnection);
    Connection. Open ();
    return connection;
}
Gets the MySQL connection database object. Mysqlconnection
//public mysqlconnection openconnection ()
//{
//mysqlconnection connection = new Mysqlco Nnection (mysqlconnectionstring);
Connection. Open ();
return connection;
//}

Note: If you need to replace the MySQL database with a function that will get the SQL Server's connection database object, uncomment the MySQL connection's function, and modify the connection information for yourself.

Query () Method:
Query () is a idbconnection extension method that is overloaded, extracts information from a database, and populates our business object model.

First, create a class that is the model of the database's Columncat table. Public
class Columncat
{public
    int Id {get; set;}
    public string Name {get; set;}
    Public DateTime ModifiedOn {get; set;}
    public int ParentID {get; set;}
}

Gets a collection of Columncat objects. Public
ienumerable<columncat> selectcolumncats ()
{
    using (IDbConnection conn = OpenConnection ())
    {
        const string query = ' SELECT * from ' Columncat ORDER by ID Desc ";
        Return Conn. Query<columncat> (Query,null);
    }

As simple as this, embedding SQL directly in an example can easily be extended to a stored procedure, which allows the column in the result set to correspond to the properties of the business object Model (COLUMNCAT).

The following set shows the classification using the above collection.
list<columncat> allcolumncat =selectcolumncats (). Tolist<columncat> ();
foreach (Columncat Cat in Allcolumncat.where (c => C.parentid = = 0))
{
    Response.Write ("name==>" + cat). Name + "\ t");
    Response.Write ("Time ==>" + Cat.) ModifiedOn + "T");
    Response.Write ("<br/>");

    foreach (Columncat C in Allcolumncat
                . Where<columncat> (subcolumncat => Subcolumncat.parentid = = Cat. ID))
    {
        Response.Write ("&nbsp;&nbsp;++++");
        Response.Write ("name==>" + c.name + "T");
        Response.Write ("Time ==>" + C.modifiedon + "T");
        Response.Write ("<br/>");
    }
The first level and level two categories are displayed on the page, and if you use a recursive, it's easy to achieve an infinite class of categories (you know).

Gets a single Columncat object. Public
columncat selectcolumncat (int columncatid)
{
    using (IDbConnection conn = OpenConnection ())
    {
        const string query = "SELECT * from Columncat where id= @id"; Return
        Conn. Query<columncat> (query, new {Id=columncatid})
                        . Singleordefault<columncat> ();
    }

Here we pass a parameter to the query method, the argument can be any object, its properties match the parameters of the SQL in the query, because query always returns a collection, we just call the Singleordefault method, because we know always to return 0 or 1 rows.

Dapper can also load a populated nested object, consider a situation that takes into account the category attributes of the news, returns the class object,
//We create a column with the classes public class
Column
{
    public int Id {get; set;}
    public string Name {get; set;}
    Public DateTime ModifiedDate {get; set;}
    Public Columncat Columncat {get; set;}
}

Next we're going to populate our business objects. Public
ilist<column> Selectcolumnswithcolumncat ()
{
    using (IDbConnection conn = OpenConnection ())
    {
        const string query = ' Select C.id,c.name,c.modifieddate,c . Columncatid
        , cat.id,cat.[ Name],cat. Modifiedon,cat. ParentID from [Column] as C left
        outer join Columncat as Cat on C.columncatid=cat.id ";
        Return Conn. Query<column, Columncat, column> (query
               , column, Columncat) => {column. Columncat = Columncat; return column; }
               , NULL, NULL, FALSE, "Id", NULL, NULL. Tolist<column> ();
    }

Note: 1, when populating nested objects, the Tolist<> method must be executed, otherwise the return ExecuteReader requires open and available connections. The current state of the connection is closed, and a single object does not have an error, estimating that the connection was closed after the using ended, and that the nested object performed the ExecuteReader at the time of the map, and had to return to the list collection before the using ended.
2, the parameters of nested objects are more, mainly the first two parameters, other parameters can not be set to NULL, but in version 4.0 can write only two parameters, other parameters have default values. The special note is Spliton, this parameter cannot be empty, otherwise will report the object as a reference error. "The Spliton parameter means to read the split column of the second object, to start reading the second object from which column, and to set this argument to" id "if the table's Self growth column is an ID.

Execute method:
Just as the query method retrieves data, the Execute method does not retrieve the data, but it is very similar to the Query method, but it always returns the total (number of rows affected) rather than a collection of objects such as insert Update and delete.

Next, add a category to the database public
int Insertcolumncat (columncat cat)
{
    using (IDbConnection conn = OpenConnection ()
    {
        const string query = "INSERT into Columncat ([Name],modifiedon,parentid)
        values (@name, @ModifiedOn, @ ParentID) ";
        int row = conn. Execute (query,cat);
        The ID of the update object is the new ID in the database, if you do not need to get the new object after the increase,
        //Simply add the object to the database, you can comment out the following line.
        setidentity (Conn,id=>cat.    Id=id, "id", "columncat"); return
        row;

    }

public void Setidentity (IDbConnection conn, action<int> setid,string PrimaryKey
                          , string tablename)
{
    if (string. IsNullOrEmpty (PrimaryKey)) PrimaryKey = "id";
    if (string. IsNullOrEmpty (tablename))
    {
        throw new ArgumentException ("TableName parameter cannot be empty, table name for Query");
    }
    string query = String. Format ("select Max ({0}) as Id from {1}", PrimaryKey
                         , tablename);
    NEWID identity = conn. query<newid> (query, NULL). Single<newid> ();
    SetId (identity. ID);

public class NewId
{public
    int Id {get; set;}
}

Because dapper is automatically bound by the properties of the class, the NEWID class is added to get the ID after the object is added, and the use of the @ @identity, Net3.5, is always an error, so use the Max function to get it. Of course, if you don't need to get the ID of an updated object, you can use Setidentity, which is generic.

Compiled dapper source code generated by the Net4.0 under the use of the new dynamic Net4.0 can be used, the
implementation of//setidentity will be very convenient. As follows: public
void Setidentity<t> (IDbConnection conn, action<int> setId)
{
    Dynamic identity = Connection. Query ("SELECT @ @IDENTITY as Id"). Single ();
    T newId = (t) identity. Id;
    SetId (newId);
}

Update a Category: public
int Updatecolumncat (columncat cat)
{
    using (IDbConnection conn = OpenConnection ())
    {
        const string query = "Update columncat set name= @Name
                          , modifiedon= @ModifiedOn, parentid= @Parentid where id=@ ID ";
        Return Conn. Execute (Query,cat);
    }

Delete a Category: public
int Deletecolumncat (columncat cat)
{
    using (IDbConnection conn = OpenConnection ())
    {
        Const string query = "Delete from Columncat where id= @id";
        Return Conn. Execute (query, cat);
    }

Here's an introduction to Dapper's advanced usage

Dapper examples of transaction processing, such as deleting categories and deleting all news under categories. or delete the product at the same time,
//delete all the pictures associated with the Product picture table. public
int Deletecolumncatandcolumn (columncat cat)
{
    using (IDbConnection conn = OpenConnection ())
    {
        const string deletecolumn = "Delete from [Column] where C Olumncatid= @catid ";
        Const string Deletecolumncat = "Delete from Columncat where id= @Id";

        IDbTransaction TRANSACTION = conn. BeginTransaction ();
        int Row=conn. Execute (DeleteColumn, new {catid =cat). Id},transaction,null,null);
        Row + = conn. Execute (Deletecolumncat, new {id=cat). Id},transaction,null,null);
        Transaction.commit ();
        return row;
    }
From:http://www.cnblogs.com/abc8023/p/3425500.html

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.