使用像应用程序的功能

时间:2013-08-07 14:05:21

标签: asp.net-mvc asp.net-mvc-4 code-first

在申请之前,我使用了一个功能。我把它添加到我的sqlserver - >数据库 - >程序性--->功能--->比例值函数

在我使用的应用程序中,如下所示:

         dbo.MyFunc(_txt.text);

但现在我需要在我的项目中使用此功能。它的mvc4网站。 有可能这样使用吗?我应该在哪里添加这个功能? 当然我确实喜欢应用程序,但db.MyFunc()在我的课程中无法识别。

所以,我的项目是CodeFirst。

2 个答案:

答案 0 :(得分:0)

当您使用代码优先DB方法时,代码更改将反映在SQL Server DB中。所以你必须在C#中实现它 以下是一个例子。来自How to: Create and Run a CLR SQL Server User-Defined Function

using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    public const double SALES_TAX = .086;

    [SqlFunction()]
    public static SqlDouble addTax(SqlDouble originalAmount)
    {
        SqlDouble taxAmount = originalAmount * SALES_TAX;

        return originalAmount + taxAmount;
    }
}

答案 1 :(得分:0)

如果您只想直接访问此特定功能:

public Object MyFunc(String txt_text)
{
    Object result = null;

    String connectionstring = "DataSource=.\SQLEXPRESS;"
                            + "Initial Catalog=DEMO;"
                            + "Integrated Security=True"; // or whatever you use....
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        using (SqlCommand command = new SqlCommand("SELECT dbo.Myfunc(@p1)", connection))
        {
            command.CommandType = CommandType.Text;
            command.Parameters.AddWithValue("@p1", txt_text);
            result = command.ExecuteScalar();
        }
    }

    return result;
}

这将建立与数据库的连接并执行该标量值函数,然后将结果放在result中。这会使任何其他数据库基础结构脱离等式,只允许您直接调用SQL函数。