EF 6.x和具有表值参数的函数

时间:2016-05-19 07:20:36

标签: c# sql-server entity-framework sql-server-2012 entity-framework-6

我有一个DB函数,需要一个表值参数作为参数(@c)。

CREATE TABLE Test
(
    CD varchar(10) not null
)
GO

INSERT INTO Test VALUES ('TEST')
GO

CREATE TYPE [CdTable] AS TABLE (CD varchar(10));
GO

CREATE FUNCTION TestTbl ( @x varchar(10), @c CdTable READONLY )
RETURNS TABLE
AS
RETURN
    SELECT t.CD
    FROM test t
    JOIN @c c ON t.CD = c.CD OR c.CD IS NULL
    WHERE t.CD = @x
GO

DECLARE @tt AS CdTable;
INSERT INTO @tt VALUES ('TEST');
SELECT * FROM TestTbl('TEST', @tt);

DELETE FROM @tt;
INSERT INTO @tt VALUES (NULL);
SELECT * FROM TestTbl('TEST', @tt);
GO

该功能是在EF Designer(数据库优先)中构建的,如DbContext中所示:

    [DbFunction("MyDbContext", "TestTbl")]
    public virtual IQueryable<TestTbl_Result> TestTbl(Nullable<System.String> x)
    {
        var xParameter = user.HasValue ?
            new ObjectParameter("x", x) :
            new ObjectParameter("x", typeof(System.String));

        return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<TestTbl_Result>("[MyDbContext].[TestTbl](@x)", xParameter);
    }

如果我调用此函数只传递可用的x / @ x参数,我会得到以下异常:

ex  {"An error occurred while executing the command definition. See the inner exception for details."}  System.Exception {System.Data.Entity.Core.EntityCommandExecutionException}
ex.InnerException   {"An insufficient number of arguments were supplied for the procedure or function TestTbl."}    System.Exception {System.Data.SqlClient.SqlException}

我不知道如何将@c参数传递给函数。有人可以帮忙吗?

提前致谢。

p.s。:我正在使用MS SQL 2012(或更新版)

1 个答案:

答案 0 :(得分:0)

您应该使用另一个方法ExecuteStoreQuery,它允许指定表值参数(SqlDbType.Structured)。

    using (var table = new DataTable ())
    {
        table.Columns.Add("cs", typeof(string));
        foreach (var item in ITEMS)
            table.Rows.Add(item.CD.ToString());

        var param1 = new SqlParameter("@x", SqlDbType.NVarChar)
        {
            Value = myValue
        };
        var param2 = new SqlParameter("@c", SqlDbType.Structured)
        {
            Value = table
        };

        ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<TestTbl_Result>(
            "select * from [TestTbl](@x, @c)", param1, param2);

    }