ABP Framework uses dapper to access databases through SQL

Source: Internet
Author: User
Tags sql client sqlite database

In order to prevent the non-provision of the original web site reprint, Special here Add the original link:
Http://www.cnblogs.com/skabyy/p/7517397.html

This article we implement the database access. We will implement two kinds of database access methods to access a SQLite database-access using ORM maps implemented by NHibernate and access to SQL statements using the dapper implementation. Then complete the previous unfinished CreateTweet and GetTweets interface.

Before you begin, do some preparatory work and create the module for the domain layer:

public class MyTweetDomainModule : AbpModule{    public override void Initialize() { IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly()); }}

MyTweetApplicationModuleadd a dependency to the pair at the same time MyTweetDomainModule :

[DependsOn(typeof(MyTweetDomainModule))]public class MyTweetApplicationModule : AbpModule

Install NuGet packages Abp.NHibernate to MyTweet.Domain and MyTweet.Infrastructure .

Below we will complete these steps to achieve database access:

    1. Configure Database connections
    2. Create tweet a new table and the corresponding model type
    3. Repository to implement Access data
    4. Accessing the database through SQL with dapper implementation
Configuring database connections using Fluent NHibernate

The database we use here is the SQLite database, and the configuration of the other databases is similar. We will connect to App_Data a SQLite database under the folder. Creates LocalDbSessionProvider a new class and configures the database connection at the constructor. Due to the LocalDbSessionProvider implementation of the interface ISingletonDependency , the module is initialized LocalDbSessionProvider with an IOC container in the form of a singleton.

PublicClassLocaldbsessionprovider:Isessionprovider,Isingletondependency,idisposable{Protected Fluentconfiguration Fluentconfiguration {GetPrivateSet }Private Isessionfactory _sessionfactory;PublicLocaldbsessionprovider () {fluentconfiguration = Fluently.configure ();Database connection stringvar connstring =The Data source=| datadirectory| mysqlite.db; "; FluentconfigurationConfigure the connection string. Database (SQLiteConfiguration.Standard.ConnectionString (connstring))//Configure ORM. Mappings (M = m.fluentmappings.addfromassembly (assembly.getexecutingassembly ())); //generated session factory _sessionfactory = Fluentconfiguration.buildsessionfactory ();} private isession _session; public isession Session {get {if ( _session! = null) {//each visit flush the previous session. Here are the efficiency and multithreading problems, for the moment, it will be changed later. _session. Flush (); _session. Dispose (); } _session = _sessionfactory.opensession (); return _session;} } public void dispose (    

Each time you use the session, you simply put the last session flush , and then open a new session. This can be an issue of efficiency and multi-threaded conflicts. This is simply a simple implementation that is used first to show how to implement a database link. This problem is resolved when the work unit (UoW) is behind.

In order to NHibernate can create a connection to SQLite, but also need System.Data.SQLite.Core to install MyTweet.Web (other databases to install other appropriate packages).

New tweetTable and the corresponding model type

We use tweet tables to store tweet data. The Tweet data table interface and the corresponding model properties are as follows:

Database Fields Model Property type Description
pk_id PkId string Primary key
content Content string Content
create_time CreateTime string Creation time

Create a new mysqlite.db file using the SQLite tool and create a new table tweet .
Then copy the Mysqlite.db file to the App_Data folder.

CREATE table  ' tweet ' (text,  ' content ' TEXT, Span class= "hljs-string" > ' create_time ' text  not null, PRIMARY key (      

Next, create a new model class Tweet and map TweetMapper . Tweetinheritance Entity<string> , where the string representation Tweet of the primary key Id is string of type. TweetMapperinheritance ClassMap<Tweet> , when the above LocalDbSessionProvider constructor executes to .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())) this method, it searches for subclasses in the Assembly in a reflective manner ClassMap<T> , establishing a mapping of the model and database tables ( Tweet and tweet table mappings).

PublicClassTweets:entity<String>The primary key is of type string {PublicString Content {GetSet }public DateTime createtime {get; set;} public class TweetMapper: classmap<tweet>{public tweetmapper (//Disable lazy loading not.lazyload (); //map to table tweet table ( "tweet"); //primary Key mapping Id (x = x.id). Column ( "pk_id"); //field map map (x = x.content). Column ( "content"); Map (x = x.createtime). Column ( "Create_time");}           
Implement repository and add-on interface

Repository is the storage in DDD, it encapsulates the data object's deletion and modification operation. ABP NhRepositoryBase has implemented the usual additions and deletions to the function, so here only need to inherit a bit of the line.

public  Interface itweetrepository: irepository< tweet, string> {}public class tweetrepository: NhRepositoryBase <tweet, STRING>,  itweetrepository{public  Tweetrepository (base ( Iocmanager.instance.resolve<localdbsessionprovider> ()) {}}       

Finally, modify MyTweetAppService , implement the CreateTweet interface and GetTweets interface.

PublicClasscreatetweetinput{PublicString Content {GetSet }}PublicClassMytweetappservice:Applicationservice,imytweetappservice{Public Itweetrepository Tweetrepository {get; set;} public object gettweets (string msg) {return tweetrepository.getall (). OrderByDescending (x = x.createtime). ToList (); } public object createtweet (createtweetinput input) {var tweet = Span class= "Hljs-keyword" >new Tweet {Id = Guid.NewGuid (). ToString ( "N"), Content = input. Content, createtime = DateTime.Now}; var o = Tweetrepository.insert (tweet); return o;}            

Done! Test it for a moment. Insert a tweet with the postman call CreateTweet interface:

Then call the GetTweets query:

Dependency Injection of ABP

There may be classmates confused, in the only declaration of the properties of the MyTweetAppService ITweetRepository type, TweetRepository but did not make the assignment, then the object instance of this property where is it? This involves the dependency injection strategy of the ABP framework.

ABP implements its own dependency injection function based on the Castle Windsor framework. The most basic function of dependency injection is nothing more Register than registering () and parsing ( Resolve ) Two, the registration function registers the object with the IOC container, and the parsing function obtains the registered object from the IOC container according to the class name or interface name. We can directly IocManager register and parse operations directly by acquiring Castle Windsor's IOC container.

// 以单例模式注册类型TIocManager.Register<T>(Abp.Dependency.DependencyLifeStyle.Singleton);// 以临时对象模式注册类型T,解析的时候会生成T的一个新对象IocManager.Register<T>(Abp.Dependency.DependencyLifeStyle.Transient);// 从IoC容器解析已注册的类型T的对象var obj = IocManager.Resolve<T>();

There are other ways to register and parse, and refer to the ABP documentation. However, these methods are not generally required. The ABP framework has a set of dependency injection rules that make dependency injection almost transparent to developers by following best practices and conventions when writing applications.

Registration of ABP

Basically, each module's initialization method will have such a line of code:

IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

When the module is initialized, the ABP searches the assembly where the module resides, automatically registering classes that meet the general registration criteria and implement the Help interface.

General Registration

ABP automatically registers all repositories, Domain services, application services, MVC controllers, and Web API controllers. ABP determines whether the above categories are determined by determining if the corresponding interfaces are implemented. For example, the following MyAppService :

public interface IMyAppService : IApplicationService { }public class MyAppService : IMyAppService { }

Since it implements the interface IApplicationService , the ABP is automatically registered and we can IMyAppService parse out an MyAppService object.

The lifetime of a class registered through a routine is transient (temporary), and a new temporary object is generated each time it resolves.

Help interface

The ABP offers in addition ITransientDependency and ISingletonDependency two interfaces. These two interfaces are also useful before. The implemented ITransientDependency classes will be registered as transient. The implemented ISingletonDependency class is registered as a singleton.

Analysis of ABP

In addition to manual parsing, the dependency of a class can also be obtained through constructors and public property injection . This is also the most commonly used method. For example:

public class MyAppService : IMyAppService{    public ILogger Logger { get; set; } private IMyRepository _repo; public MyAppService(IMyRepository repo) { _repo = repo; }}

ILoggerInjected from a public attribute, IMyRepository injected from a constructor. The injection process is transparent to the developer, and the developer does not need to write the injected code.

QueryService-Querying data using SQL statements

In practical development, it is often necessary to use SQL directly for data access. Complex mapper can be avoided by using SQL directly when the query logic is more complex. Often complex mapper can lead to inefficient queries that can even trigger nhibernate some strange bugs. In fact, in development, we recommend using SQL queries directly for the simple ability to read data, even if the query logic is not complex. Using SQL queries directly is more convenient when debugging--copying SQL statements directly to SQL client execution to verify that the statement is correct.

The following is a brief introduction to using dapper to implement database query function. The class that encapsulates the SQL query operation we call QueryService.

First, install dapper the package to MyTweet.Infrastructure . The MyTweet.Infrastructure base class for implementing QueryService BaseQueryService :

public class    Span class= "Hljs-title" >basequeryservice: itransientdependency{ private isessionprovider _sessionprovider; protected BaseQueryService ( Span class= "Hljs-params" >isessionprovider sessionprovider) {_sessionprovider = Sessionprovider;} public ienumerable<t> query<t> (string sql, object param = null) {var conn = _ SessionProvider.Session.Connection; return Conn. query<t> (SQL, param); }} 

Dapper System.Data.IDbConnection extends the method to an interface that Query<T> executes an SQL query and maps the query structure to an IEnumerable<T> object of type. In order to use this extension method, you also need to add a statement at the beginning of the file using .

using Dapper;

QueryService is not in the general registration rules of the ABP dependency injection, so it is implemented so that BaseQueryService ITransientDependency its subclasses are automatically registered to the IOC container.

Next, in the MyTweet.Domain new class TweetQueryService , it is responsible for implementing the specific SQL query. Method SearchTweets implements a query that contains keyword all the tweets that contain keywords.

PublicInterfaceitweetqueryservice{Ilist<tweet>Searchtweets (string keyword);}PublicClassTweetqueryservice:basequeryservice, itweetqueryservice{ public TweetQueryService (base (iocmanager.instance.resolve< Localdbsessionprovider> ()) {} public IList<Tweet> searchtweets (string keyword) { Span class= "Hljs-keyword" >var sql = @ "select pk_id ID, content content, Create_time createtime From tweets where content like '% ' | | @Keyword | | ‘%‘"; return query<tweet> (sql, new {keyword = keyword??  

Finally MyTweetAppService , the interface that implements the query tweet data GetTweetsFromQS :

public ITweetQueryService TweetQueryService { get; set; }public object GetTweetsFromQS(string keyword){ return TweetQueryService.SearchTweets(keyword);} 

Test it:

End

This paper introduces the method of database access through NHibernate and dapper, and simply illustrates the ABP dependency injection strategy. Now the database connection part of the code is simply to demonstrate the simple implementation, did not do a reasonable database session management, there will be efficiency and multi-threaded conflict problems. The unit of work is added later to address these issues.

Finally, put the code link: Https://github.com/sKabYY/MyTweet-AbpDemo

ABP Framework uses dapper to access databases through SQL

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.