【问题标题】:EF 6.x and function with table-valued parameterEF 6.x 和带有表值参数的函数
【发布时间】:2016-05-19 07:20:36
【问题描述】:

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

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 设计器(数据库优先)构建的,就像在 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(或更新版本)

【问题讨论】:

  • 应该是DataTable吧?

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


【解决方案1】:

您应该使用另一种方法 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);

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 2014-09-28
    • 2016-05-23
    • 2012-01-17
    • 2023-02-08
    • 2011-06-12
    • 2021-04-14
    相关资源
    最近更新 更多