Skip to content

Custom function

so edited this page Jul 30, 2021 · 4 revisions

函数映射

1. 创建数据库函数

 CREATE FUNCTION [MyFunction](@id int)
 RETURNS VARCHAR(max)
 AS
 BEGIN
    return 'id: ' + cast(@id as VARCHAR(max))
 END

2. 定义一个方法,打上 DbFunctionAttribute 特性

public class DbFunctions
{
    [Chloe.Annotations.DbFunctionAttribute("MyFunction")]
    public static string MyFunction(int value)
    {
        throw new NotImplementedException();
    }
}

3. 在 lambda 表达式中使用

query.Select(a => new { str = DbFunctions.MyFunction(a.Id) };

注:DbFunctionAttribute 可以映射到自定义函数,亦可以映射到数据库函数。