简体   繁体   English

自定义 sql 功能流畅 nhibernate

[英]custom sql functions with fluent nhibernate

How can I use some my SQL function with Fluent NHibernate?如何将我的 SQL function 与 Fluent NHibernate 一起使用?

I have some SQL function, for example:我有一些SQL function,例如:

CREATE FUNCTION [dbo].[TestFunction] 
(
    @value1 int,
    @vlaue2 int 
)
RETURNS int
AS
BEGIN
    RETURN @value1 + @value2
END

And I whant use this function in some of my criteria queries.我想在我的一些标准查询中使用这个 function。 Can I do this and how?我可以这样做吗?怎么做?

There are a few ways to do this the easiest that I found was to provide a custom SQL Dialect that registered my function and then used Session.CreateSQLQuery to execute it.有几种方法可以做到这一点,我发现最简单的方法是提供自定义 SQL 方言,注册我的 function 然后使用Session.CreateSQLQuery执行它

Here is a sample custom Dialect:这是一个示例自定义方言:

public class CustomMsSql2012Dialect : MsSql2012Dialect
{
    public CustomMsSql2012Dialect ()
    {          
        RegisterFunction("dbo.testfunction", new SQLFunctionTemplate(NHibernateUtil.Int32, "dbo.TestFunction(?1, ?2)"));
    }
}

Note that the function name in the first string passed to RegisterFunction is all lowercase, in my research I came across someone that said this was required but I can't find that article to cite now unfortunately.请注意,传递给RegisterFunction的第一个字符串中的 function 名称都是小写的,在我的研究中,我遇到有人说这是必需的,但不幸的是我现在找不到要引用的文章。

How to use the dialect:如何使用方言:

MsSqlConfiguration.MsSql2012.ConnectionString("connectionStringHere")
    .Dialect<EkaMsSql2012Dialect>();

How to call the function:如何调用 function:

Session.CreateSQLQuery("SELECT dbo.TestFunction( :value1, :value2 )")
     .SetString("value1", 5)
     .SetString("value2", 6)
     .UniqueResult<int>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM