Farseer.net Lightweight ORM Open Source Framework v1.x Primer: Database context

Source: Internet
Author: User

Navigation

Catalog: Farseer.net Lightweight ORM Open source Framework Catalog

Previous: Farseer.net Lightweight ORM Open source framework v1.x : Database configuration file

Filed under: Farseer.net Lightweight ORM Open source framework v1.x : Table entity class mappings

Objective

The above describes the use of database configuration, the way to build a database link we know how to do it.

In fact, so far we still have not talked about the code aspect, spent a lot of space to explain, mainly want to go to the next, or a come up to explain this to explain that, listen to the confused, but not the effect.

This is important because it is the most basic class we use when using farseer.net:DbContext(a concept with entityframework DbContext)

Database context

Literally, we know: It's a bridge between our program (business) and database, and when we curd tables (entity classes), we need to let the entity classes know what kind of database I need to access.

and the database context, is to tell our entity class, which database type should be connected to access.

In Farsser.net, the class that corresponds to the database context is:DbContext, which is what we need to inherit from, and in this class, encapsulate the attributes of the entity class we need.

constructor function
        /// <summary>        ///connect to database through database configuration/// </summary>        /// <param name= "Dbindex" >Database Options</param>        protectedDbContext (intDbindex =0)        /// <summary>        ///connect to a database by customizing the data link/// </summary>        /// <param name= "connectionString" >Database connection String</param>        /// <param name= "DbType" >Database Type</param>        /// <param name= "CommandTimeout" >SQL Execution time-out</param>        protectedDbContext (stringconnectionString, DatabaseType dbType = Databasetype.sqlserver,intCommandTimeout = -)

A constructor with an int dbindex parameter, passing in the Configuration index entry of the Dbconfig (if we have multiple databases configured).

The default setting for parameter INT Dbindex = 0 , we don't need additional code to set it unless you need a different database configuration. Or, you can use custom constructs to achieve different database access at run time, depending on your business needs.

The last constructor is to specify the connection mode if we do not use the Dbconfig database configuration item .

We did not use the Web. config (or app. config) configuration item above, in fact the blogger did not like to set the custom configuration item in Web. config, and felt that it would be "aggressive".

Derived classes for DbContext

Dbcontext<tpo> In fact, this class is just one more attribute:

        /// <summary>        /// Static Instances         /// </summary>         Public Static Get return New false }; } }

It's just that we don't need to instantiate the using (var db = new DbContext ()) to invoke.

Many times, we are just a very simple operation. For example, the insertion of only one piece of data:

// Inserting Data Table. Data. User. Insert (new"yy" });

Without needing:

using (varnew  Table ()) {    new"xx"  };     // Inserting Data    Context. User. Insert true );    Context. SaveChanges ();}
Context of the actual project

It inherits from the dbcontext<tpo>:

1     /// <summary>2     ///Database Context3     /// </summary>4      Public classTable:dbcontext<table>5     {6         /// <summary>7         ///The default is 0 o'clock, do not display fill this item, currently just to demonstrate8         /// </summary>9          PublicTable ():Base(0) { }Ten  One[Set (Name ="Members_user")] A          PublicTableset<uservo> User {Get;Set; } -  -[Set (Name ="Members_role")] the          PublicTablesetcache<userrolevo> Userrole {Get;Set; } -[Set (Name ="members_orders")] -          PublicTableset<ordersvo> Orders {Get;Set; } -  +[Set (Name ="members_orders")] -[Sortdelete (Name ="Isdeletebyat", FieldType = eumsortdeletetype.datetime, Value =true)] +          PublicTableset<ordersvo> Ordersat {Get;Set; } A  at[Set (Name ="members_orders")] -[Sortdelete (Name ="Isdeletebybool", FieldType = eumsortdeletetype.bool, Value =true)] -          PublicTableset<ordersvo> Ordersbool {Get;Set; } -  -[Set (Name ="members_orders")] -[Sortdelete (Name ="Isdeletebynum", FieldType = eumsortdeletetype.number, Value =3)] in          PublicTableset<ordersvo> Ordersnum {Get;Set; } -}

Tableset is equivalent to the set class of EntityFramework, which is described in the next article.

Properties of the DbContext
        /// <summary>        ///database providers (characteristics of different databases)/// </summary>         PublicAbsdbprovider Dbprovider {Get;Private Set; } /// <summary>        ///Database Operations/// </summary>         PublicDbexecutor DataBase {Get;Private Set; } /// <summary>        ///Performing Database Operations/// </summary>         PublicExecuteSQL Executeor {Get;Private Set; } /// <summary>        ///Mapping Relationships/// </summary>         PublicContextmap Map {Get;Private Set; }

  dbprovider: Database providers, different database types should have corresponding implementation classes, such as: Sqlserverprovider. Some of the features of different databases are implemented inside.

  Database: It is the SQL that is generated after the final commit to the databases for interaction.

  Executeor: The generic conversion is performed by the object/datatable type returned after database execution. The difference between it and database is that it is more area-to-business data type.

  map: Refers to the database context mapping information, including some property information.

Methods of DbContext
/// <summary> /// Save Changes /// ismergecommand=true: Submit SQL to database only once /// </summary> /// <param name= "Isolation" > enable transaction operations by default </param>  Public int SaveChanges (booltrue)

By naming the method, we can associate it with a save commit when the data is changed.

Note that the query to the database does not need to call this method, only when the data is updated, deleted, inserted, only need to call.

However, if you are using static mode , that is, you do not need the new DbContext () mode, you do not need to call SaveChanges. This is provided as a convenience (syntactic sugar).

It has a parameter bool isolation = True, which is committed by default as a transaction . If you do not want this, you can display the incoming false.

Summarize

This article, we have learned the database context of the code to write, although the length is very long, but in fact, it is one thing, simple can not be simpler.

Navigation

Catalog: Farseer.net Lightweight ORM Open source Framework Catalog

Previous: Farseer.net Lightweight ORM Open source framework v1.x : Database configuration file

Filed under: Farseer.net Lightweight ORM Open source framework v1.x : Table entity class mappings

Advertising time

QQ Group:116228666 (farseer.net Open source frame exchange) Please specify:farseer.net

Farseer.net is an ORM framework + Common tool + extension collection.

Farseer implication: Prophets and seers usually offer tricks and strategies in certain situations. Also hope that the framework can provide you with maximum convenience.

ORM: The English name is:object relational(relationship) Mapping(map)

Farseer.net's goal is: Quick start, rapid development, simple and convenient.

1Table.data.User. Where (O=>o.id = =1). toentity ();2Table.data.User. Where (O=>o.id >1). ToList ();3Table.data.User. Where (o=>o.id! =0). Delete ();4Table.data.User. Where (o=>o.id! =0).Addup(O=>o.logincount,1);5Table.data.User. Where (O=>o.id = =1).Update(Newuser{UserName ="NewName" });6Table.data.User.Insert(Newuser{UserName ="NewName"});

Farseer.net Lightweight ORM Open Source Framework v1.x Primer: Database context

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.