ArticleDirectory
- Iruntimemethodhqlgenerator
- Ihqlgeneratorformethod
- Ihqlgeneratorforproperty
- Basehqlgeneratorformethod
- Basehqlgeneratorforproperty
Public class adddaysgenerator: basehqlgeneratorformethod
{
Public adddaysgenerator ()
{
Supportedmethods = new [] {reflectionhelper. getmethoddefinition <date> (D => D. adddays (0 ))};
}
# Region overrides of basehqlgeneratorformethod
Public override hqltreenode buildhql (methodinfo method, expression targetobject, readonlycollection <expression> arguments, hqltreebuilder treebuilder, ihqlexpressionvisitor visitor)
{
Return treebuilder. methodcall ("adddays", new []
{
Visitor. Visit (arguments [0]). asexpression (),
Visitor. Visit (targetobject). asexpression ()
});
}
# Endregion
}
Public class adddaysgeneratorregistry: defaultlinqtohqlgeneratorsregistry
{
Public adddaysgeneratorregistry ()
{
Registergenerator (reflectionhelper. getmethoddefinition <date> (D => D. adddays (0), new adddaysgenerator ());
}
}
Public class customdialect: mssql2008dialect
{
Public customdialect ()
{
Registerfunction ("adddays", new sqlfunctiontemplate (nhibernateutil. datetime, "dateadd (DD ,? 1 ,? 2 )"));
}
}
As you can see, this picks up our method adddays defined on our custom date class. This means that we can do something like:
Query = query. Where (Dc => (DC. enddatereminderperiod! = NULL & (DC. enddate). adddays (0-dc.enddatereminderperiod.value) ==_ reminderdate) |
(Dc. realenddatereminderperiod! = NULL & (DC. realenddate). adddays (0-dc.realenddatereminderperiod.value) = _ reminderdate )));
Where in this example xxreminderperiod is an int and xxdate is a date property.
I "think" that this fails because the return type of the function is datetime and so when it gets to the capacity part of the method, its trying to put the _ reminderdate into a datetime. but as I am sure you have guessed, _ reminderdate is a date.
I was trying to change the function to use my custom transaltor for the return type, but it seems that sqlfunction only accepts a itype and not an iusertype.
Any thoughts?
Content of this section
- Series Introduction
- Overview
- Custom extension mechanism of LINQ provider
- Implementation of custom extensions of LINQ provider
- Conclusion
- References
Series Introduction
Nhibernate3.0 profiling SeriesThe new features and applications of nhibernate3.0 and their applications are fully revealed in configuration, mapping, query, session policy, and application respectively.ProgramBased on nhibernte3.0. If you are not familiar with nhib.pdf, you can quickly get started with the nhibana travel series Article navigation series. If you are already using nhib.pdf, please keep upNhibernate3.0 profiling SeriesRight.
- Nhib.pdf topics: http://kb.cnblogs.com/zt/nhibernate/
- Nhibernate site: http://nhforge.org/
- Nhib.pdf Reference document: http://nhforge.org/doc/nh/en/
- Get Nhibernate address: http://sourceforge.net/projects/nhibernate/
Overview
In addition to the standard query operator and the two strong queries (eagerfetching) and query cache (querycacheable) that are unique to nhib.pdf, we can also define the extension of the LINQ provider.
Custom extension mechanism of LINQ provider
In nhib.pdf, almost all object-oriented query languages (hql, criteria, and queryover) are scalable, and LINQ is no exception. We can extend the custom LINQ-provider and convert the LINQ Extension Method to SQL. Next, let's take a look at the extended LINQ provider mechanism provided by nhib.pdf.
Ilinqtohqlgeneratorsregistry Interface
Provides a unified registration interface for hql-generators. When building sessionfactory, nhibators registers the provided hql-generators.
Linqtohqlgeneratorsregistryfactory registered factory
The hql-generators registration factory is provided. By default, nhibloud built-in support is registered. for example, the attributes and methods provided by the datetime type, the attributes and methods provided by the string type, and the methods provided by queryable and enumerable.
You can use the configuration"Linqtohql. generatorsregistry"The configuration section or the configuration class providesLinqtohqlgeneratorsregistry Extension MethodRegister and implement the ilinqtohqlgeneratorsregistry interface to customize the LINQ provider extension.
Defaultlinqtohqlgeneratorsregistry registration class
By default, Nhibernate built-in support for the Nhibernate. LINQ query registration class inherits the ilinqtohqlgeneratorsregistry interface.
Three hql-generators interfaces: iruntimemethodhqlgenerator
To register runtime methods, icollection <t> sets the contains method and the extension method with linqextensionmethodattribute.
Ihqlgeneratorformethod
Generate hql methods, such as the any, all, Min, Max, and contains methods of queryable and enumerable classes; string startswith, endswith, contains, equals, tolower, tolowerinvariant, toupper, toupperinvariant, substring, indexof, replace method and Extension Method with linqextensionmethodattribute, inside nhibors, it is used to identify and convert the visitors class.
Ihqlgeneratorforproperty
Generate hql attributes, such as year, month, day, hour, minute, second, and date attributes of datetime type, and length attributes of string type. Inside nhibors, it is used to identify and convert attributes of the visitors class.
Two abstract classes of hql-generators: basehqlgeneratorformethod
Basehqlgeneratorformethod abstract class implements the ihqlgeneratorformethod interface. The hql-generators used to define the method.
For example, nhibith provides hql-generators for the string startwith () method:
Basehqlgeneratorforproperty
Basehqlgeneratorforproperty abstract class implements the ihqlgeneratorforproperty interface. Hql-generators used to define attributes.
For example, hql-generators of the string type Length attribute is provided in nhib.pdf:
Knowing the above content, I believe you can customize a LINQ provider extension.
Implementation of custom extensions of LINQ provider
Taking the string type as an example, we use the islike Extension Method to extend the string type, imitating the like clause in SQL.
1
Use the islike Extension Method to extend the string type,CodeAs follows:
// Code snippets copyright http://lyj.cnblogs.com/ Public static class Mylinqextensions { Public static bool Islike ( This string Source, String Pattern) {pattern = RegEx . Escape (pattern); pattern = pattern. Replace ( "%" ,".*? " ). Replace ( "_" , "." ); Pattern = pattern. Replace ( @"\[" , "[" ). Replace ( @ "\]" , "]" ). Replace ( @ "\ ^" , "^" ); Return RegEx . Ismatch (source, pattern );}}
2. Implementation of hql-generators in the islike Extension Method
After creating the extension method, you can use the extension in the memory. However, we need nhibies to translate it into persistence-queries, that is, to convert it to SQL. Similar to the built-in implementation of nhibors, we need to create a generators:
// Code snippets copyright http://lyj.cnblogs.com/ Public class Islikegenerator : Basehqlgeneratorformethod { Public Islikegenerator () {supportedmethods = New [] { Reflectionhelper . Getmethoddefinition () => Mylinqextensions . Islike ( Null , Null ))};} Public override Hqltreenode Buildhql ( Methodinfo Method, Expression Targetobject, Readonlycollection < Expression > Arguments, Hqltreebuilder Treebuilder, Ihqlexpressionvisitor Visitor ){ Return Treebuilder. Like (visitor. Visit (arguments [0]). asexpression (), visitor. Visit (arguments [1]). asexpression ());}}
3. register the islike Extension Method hql-Generators
We inherit the built-in support of nhib.pdf. LINQ to query registration classes in nhib.pdf by default, so that we can append our custom hql-generators.
// Code snippets copyright http://lyj.cnblogs.com/Public classMylinqtohqlgeneratorsregistry:Defaultlinqtohqlgeneratorsregistry{PublicMylinqtohqlgeneratorsregistry () {registergenerator (Reflectionhelper. Getmethoddefinition () =>Mylinqextensions. Islike (Null,Null)),NewIslikegenerator());}}
4. Configure the custom LINQ provider Extension
To use the islike Extension Method to query DB data, we need to configure our custom linqtohqlgeneratorsregistry. If you use the configuration file, you need to use linqtohql. generatorsregistry:
If loquacious-configuration is used:
// Code snippets copyright http://lyj.cnblogs.com/Configuration. linqtohqlgeneratorsregistry <Mylinqtohqlgeneratorsregistry> ();
5. Use the islike Extension Method
// Code snippets copyright http://lyj.cnblogs.com/VaRUsers = session. query <User> (). Where (O => O. Name. islike ("% Yongjing %"). Tolist ();
6. Execution result
Conclusion
This article describes the custom extension mechanism and implementation of the linq provider.
References
Fabio maulo: nhibw.linq provider Extension
Nhib1_jira: add support for user-provided extensions to the LINQ provider
I hope this article will help you.