NHibernate3 anatomy: nhibernate.linq Custom extension of the query article

Source: Internet
Author: User

Series Introduction

NHibernate3.0 Analysis Series from configuration, mapping, query, session strategy, Applications and other aspects of the comprehensive disclosure of NHibernate3.0 new features and applications and the integration of various applications, based on the NHibernte3.0 version. If you are not familiar with nhibernate, you can quickly read the NHibernate series of articles navigation series to get started, if you are already using NHibernate, then please follow the NHibernate3.0 anatomy series .

    • NHibernate Special topic: http://kb.cnblogs.com/zt/nhibernate/
    • NHibernate Official site: http://nhforge.org/
    • NHibernate Reference Document: http://nhforge.org/doc/nh/en/
    • Get NHibernate Address: http://sourceforge.net/projects/nhibernate/
Overview

Nhibernate.linq In addition to providing the standard query operators and the NHibernate-specific two strong queries (eagerfetching) and query Caching (querycacheable), we can also define our own LINQ Provider extension.

LINQ Provider Custom extension mechanism

In NHibernate, almost all object-oriented query languages (HQL, Criteria, queryover) are extensible, and LINQ is no exception. We can extend the custom linq-provider and convert the LINQ extension method to SQL. Here's a look at NHibernate's external LINQ provider extension mechanism.

Ilinqtohqlgeneratorsregistry interface

Provides a unified registration interface for Hql-generators, NHibernate registers the hql-generators provided when build sessionfactory.

Linqtohqlgeneratorsregistryfactory Registered Factory

Provides hql-generators registered factory, default registration NHibernate built-in support for NHIBERNATE.LINQ queries, such as the properties and methods provided by the DateTime type, properties and methods provided by the string type, Methods provided by Queryable and Enumerable.

You can use the configuration section of the "Linqtohql.generatorsregistry" or the Config class to provide Linqtohqlgeneratorsregistry extension Method registration implements the Ilinqtohqlgeneratorsregistry interface to customize the LINQ provider extension.

Defaultlinqtohqlgeneratorsregistry Registration Class

The default NHibernate built-in support for NHIBERNATE.LINQ query registration classes, inheriting the Ilinqtohqlgeneratorsregistry interface.

Three kinds of Hql-generators interface: Iruntimemethodhqlgenerator

The Contains method that registers the,icollection<t> collection with the run-time method, with Linqextensionmethodattribute extension methods.

Ihqlgeneratorformethod

Generation of method hql, such as any, all, Min, Max, Contains method for queryable and enumerable classes, string-type StartsWith, EndsWith, Contains, Equals, ToLower, Tolowerinvariant, ToUpper, Toupperinvariant, Substring, IndexOf, The Replace method and the extension method with Linqextensionmethodattribute, nhibernate internally used to identify and transform the visitors class.

Ihqlgeneratorforproperty

A property is HQL generated, such as the year of the DateTime type, Month, day, Hour, Minute, Second, Date property, and the length property of the string type. NHibernate is used internally to identify and transform the properties of the visitors class.

Two kinds of hql-generators abstract class: Basehqlgeneratorformethod

The Basehqlgeneratorformethod abstract class implements the Ihqlgeneratorformethod interface. The hql-generators used to define the method.

For example, the NHibernate built-in provides a hql-generators implementation of the String type Startwith () method:

Basehqlgeneratorforproperty

The Basehqlgeneratorforproperty abstract class implements the Ihqlgeneratorforproperty interface. The hql-generators used to define the property.

For example, the NHibernate built-in provides a hql-generators implementation of the string type length property:

Knowing the above, I believe you can customize a LINQ provider extension.

LINQ Provider Custom Extension implementations

We use the string type as an example to extend the string type using the Islike extension method, mimicking the LIKE clause in SQL.

1.Linq extension method

Use the Islike extension method to extend the string type with the following code:

//code Snippets Copyright http://lyj.cnblogs.com/Public Static Classmylinqextensions{Public static BOOLIslike (This stringSourcestringPattern) {pattern =Regex.        Escape (pattern); Pattern = pattern. Replace ("%",".*?"). Replace ("_","."); Pattern = pattern. Replace (@"\[","["). Replace (@"\]","]"). Replace (@"\^","^");returnRegex.    IsMatch (source, pattern); }}
Hql-generators implementation of 2.IsLike extension method

Once you have created the extension method, you can use the extension in memory. But we need nhibernate to translate it into a persistent query (persistence-queries), which needs to be converted to SQL. Like the NHibernate built-in implementations, we need to create a generators:

//code Snippets Copyright http://lyj.cnblogs.com/Public classIslikegenerator:Basehqlgeneratorformethod{ PublicIslikegenerator () {supportedmethods =New[]         {Reflectionhelper. Getmethoddefinition (() =mylinqextensions. Islike (NULL,NULL))}; }Public OverrideHqltreenodeBUILDHQL (MethodInfoMethodExpressionTargetObject,ReadOnlyCollection<Expression> Arguments,HqltreebuilderTreebuilder,IhqlexpressionvisitorVisitor) {returnTreebuilder.like (visitor. Visit (Arguments[0]). Asexpression (), visitor. Visit (Arguments[1]).    Asexpression ()); }}
3. Registering the Islike extension method hql-generators

We inherit the default NHibernate built-in support for the NHIBERNATE.LINQ query registration class, which allows us to attach our custom hql-generators.

//Code Snippets Copyright http://lyj.cnblogs.com/public class MyLinqToHqlGeneratorsRegistry: DefaultLinqToHqlGeneratorsRegistry{    public MyLinqToHqlGeneratorsRegistry()    {        RegisterGenerator(ReflectionHelper.GetMethodDefinition(            () => MyLinqExtensions.IsLike(null, null)),new IsLikeGenerator());    }}
4. Configure custom LINQ Provider Extensions

Using the Islike extension method to query DB data, we need to configure our custom linqtohqlgeneratorsregistry, and if you use a configuration file configuration, you need to use Linqtohql.generatorsregistry:

This is true if you use Loquacious-configuration:

//Code Snippets Copyright http://lyj.cnblogs.com/configuration.LinqToHqlGeneratorsRegistry<MyLinqToHqlGeneratorsRegistry>();
5. Using the Islike extension method
//Code Snippets Copyright http://lyj.cnblogs.com/users = session.Query<User>().Where(o => o.Name.IsLike("%永京%")).ToList();
6. Implementation results

Conclusion

This article learned about the LINQ provider Custom extension mechanism and implementation.

Copyright NOTICE: This article for Bo Master http://www.zuiniusn.com original article, without Bo Master permission not reproduced.

NHibernate3 anatomy: nhibernate.linq Custom extension of the query 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.