Application of Ormbase object/relational database mapping in MVC

Source: Internet
Author: User
Tags object model connectionstrings

The word ORM is the most frequently used when we operate the database. What the hell is it, let's take a look at some of the explanations for what it means.

Object/relational database mapping (object/relational mapping) This term represents a technique used to map objects represented by an object model to the SQL-based relational model database structure. ORM, the Object-relational Mapping (Object relational mapping), is a mapping between a relational database and a business entity object, so that we do not need to deal with complex SQL statements when it comes to manipulating business objects. Just manipulate the object as you normally do it.
Object Relational Mapping (ORM) provides conceptual, easy-to-understand methods for modeling data. An ORM methodology should be based on three core principles:
Simple: Model data in the most basic form.
Communication: The database structure is documented in a language that anyone can understand.
Accuracy: Create a properly standardized structure based on the data model.
Based on three principles, on the one hand, modelers develop enterprise entity models by gathering information from those familiar with the application but not the skilled data modelers, and the business entity designers can also apply these business entities and build enterprise application systems based on a complete separation from the data structure architecture. On the other hand, we can completely forget about the simple and dry grassland SQL statements, which are completely superfluous for the Modeler application in the ORM architecture.

Let's do a practical example of using ORM:

One, configure the connection database string in the Web. config file.

<connectionStrings>
<add name= "connectionString" connectionstring= "Data source=219.90.127.39,11433;initial catalog= Casino; User Id=sa; password=sz123456; Max Pool size=512; Min Pool size=5 "providername=" System.Data.SqlClient "/>
</connectionStrings>

Second, in Global.asax.ca, execute the initial stage of project startup, make the ConnectionString statement of connecting Database command.

protected void Application_Start ()
{
Arearegistration.registerallareas ();

ThePart.DataHelper.ORM.ORMBase.AddDataHelper ("Casino", ThePart.DataHelper.Enum.DBType.SQL,
system.configuration.configurationmanager.connectionstrings["connectionString"]. ConnectionString);

Registerglobalfilters (globalfilters.filters);
RegisterRoutes (routetable.routes);
}

Third, create the Entity Class Foundation Ormbase Object-relational database mapping base class.

" database name ", " table name ", " primary key ", " identity column field "

[Tableinfo ("Casino","Agencystatisticsrecords","ID","ID")]
public class Agencystatisticsrecords:ormbase
{
public int ID {get; set;}

public string Accounttime {get; set;}

public string AgentName {get; set;}
Public decimal Totalstakescore {get; set;}
Public decimal Totalwinlost {get; set;}
public int UserName {get; set;}
public int? Saleid {get; set;}
}

Four, business methods, object mapping relational database-table data, to obtain data objects. ---------entity classes are used directly here.   getinfo< entity class > ("fields in entities requiring querying", "Query Criteria", new object[]{}); Here new object[]{} is a number of parameters as an array of objects, passed into the database.

public string getuseragency ()
{
string BODY = null;

StringBuilder StrB = new StringBuilder ();
Strb.append ("Select ID, Accounttime, AgentName, Totalstakescore,totalwinlost, UserName, Saleid from Agencystatisticsrecords where id= ' 17 ' ");

var agency = agencystatisticsrecords.getinfo<agencystatisticsrecords> ("ID, Accounttime, AgentName, Totalstakescore,totalwinlost, UserName, Saleid "," id= ' ", New object[]{});

BODY = "{\" agentname\ ": \" "+agency. Agentname+ "\", \ "datetime\": \ "" +agency. Accounttime+ "\" "+"} ";
return body;
}

V.ThePart.DataHelper.ORM.ORMBase This object-relational mapping base class, there are many flexible value patterns for the return value of the database when it is added and censored. Let's make some summary so that we can apply the following flexibly:

1. Return directly to datatable--this is the most flexible data field that does not have to be returned, and must be a field of the entity class. Because it is in the form of a DataTable. is not an entity object. So the way SQL queries are more flexible. can be sum (), count (), or a newly generated field or table in the process of the query. For example, the DataTable field returned below has no relation to the Betrecords class field. datatable.rows[0]["Sumwinlost"] this

The winning and losing statistics field of a new student is evaluated.

<summary>
Get win/Loss statistics for user time period
</summary>
<param name= "Saleno" ></param>
<param name= "UserName" ></param>
<param name= "StartDate" ></param>
<param name= "EndDate" ></param>
<returns></returns>
public static DataTable Getusersumwin (String Saleno, String UserName, DateTime startdate, datetime EndDate) {
StringBuilder strSQL = new StringBuilder ();
Strsql.append ("Select ISNULL (SUM (Winlost), 0) as Sumwinlost from Betrecords");
String condition = "where UserName = '" + UserName + "' and Saleid = '" + Saleno + "' and [DateTime] between '" + Startdat E + "' and '" +enddate+ "";
Strsql.append (condition);

Returnbetrecords.execsqldatatable ("Casino", strsql.tostring (), New object[]{});
}

2. Returns a generic class entity collection list<t>--the entity class that needs to be mapped here, and the field names queried from the database must match the field names of the entity classes. For example:

public static list<sportsbetrecords> Sportsgetlist (String Saleid, String UserName, String ClassType, String Startime, String EndTime)
{
StringBuilder sb = new StringBuilder ("1=1 and saleid= '" + Saleid + "'"); The variable string type is declared here to load and append the query condition behind where
if (!string. IsNullOrEmpty (UserName))
{
Sb. Append ("and username=" + UserName + "'");
}
if (!string. IsNullOrEmpty (ClassType))
Sb. Append ("and gamename=" + ClassType + "'");
if (!string. IsNullOrEmpty (startime) &&!string. IsNullOrEmpty (EndTime))
Sb. Append ("and [T] between '" + convert.todatetime (startime) + "' and '" + convert.todatetime (EndTime). AddDays (1) + "'");

The entity class. getlist< entity class > ("where is the condition ", "condition parameter as an Object array")--into the database base class encapsulated getlist<t> () A series of processes inside the method pass the Where condition and the following array of parameter objects to the database as a condition
return sportsbetrecords.getlist<sportsbetrecords>(sb.) ToString (), new object[] {});
}

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.