在 SQL 服务器上创建一个用户函数,其功能与 C# 代码相同。假设它被称为“dbo.SatsFilter”。
在您的数据上下文覆盖上创建一个方法,假设它看起来像:
public bool SatisfiesFilter(string name, string filter)
{
// some sort of implementation.
}
装饰 C# 方法[Function]
and [Parameter]
属性,所以它看起来像:
[Function(Name="dbo.SatsFilter",IsComposable=true)]
public bool SatisfiesFilter([Parameter name="@name",DbType="nvarchar(50)"]string name, [Parameter name="@filter",DbType="nvarchar(50)"]string filter)
IsComposable=true
意味着它是一个函数而不是存储过程,因此可以用作更大查询的一部分。
您现在可以使用 DataContext 的此方法,它会在适当的时候转换为 SQL,或者 C# 将用于在内存中执行的查询。
另请注意,如果您只想始终使用 SQL(有时很有用),则可以在 C# 代码中调用该方法时调用 SQL:
[Function(Name="dbo.SatsFilter",IsComposable=true)]
public bool SatisfiesFilter([Parameter name="@name",DbType="nvarchar(50)"]string name, [Parameter name="@filter",DbType="nvarchar(50)"]string filter)
{
return (bool)ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod(), name, filter).ReturnValue;
}
当 C# 等效项很方便时,这不是很有用,因为这意味着对数据库的命中和一些翻译,但如果用户函数依赖于数据库状态或难以很好地转换为 C#,则它很有用