通过实体框架将数组/表传递给存储过程 [英] Passing an array/table to stored procedure through Entity Framework

查看:99
本文介绍了通过实体框架将数组/表传递给存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有C#的Entity Framework来制作Silverlight应用程序。我已经写了一些执行数据库密集型操作的存储过程,我需要在传递一些参数后从Entity Framework调用它们。在其中一个步骤中,用户选择需要更多详细信息的项目列表。这个项目列表(以整数ID数组的形式)需要传递给存储过程以检索关于这些ID的更多信息。如何将此参数传递给存储过程?

解决方案

您不能将表值参数传递给SQL,框架。



您可以做的是创建一个分隔符,如1 | 2 | 3 | 4和在SQL中创建一个Split函数,返回一个表。

  CREATE FUNCTION dbo.Split 

@RowData nvarchar(2000),
@SplitOn nvarchar(5)

RETURNS @RtnValue表

Id int identity(1,1),
数据nvarchar(100)

AS
BEGIN
声明@Cnt int
Set @Cnt = 1

While(Charindex (@ SplitOn,@ RowData)> 0)
开始
插入到@RtnValue(数据)
选择
数据= ltrim(rtrim(Substring(@ RowData,1,Charindex (@ SplitOn,@ RowData)-1)))

Set @RowData = Substring(@ RowData,Charindex(@ SplitOn,@ RowData)+ 1,len(@RowData))
设置@Cnt = @Cnt + 1
结束

插入到@RtnValue(数据)
选择Data = ltrim(rtrim(@RowData))

返回
END

然后,如果您需要根据传递给proc的分隔字符串中的所有项目从表中选择所有项目:

  SELECT * FROM SomeTable WHERE Id IN(SELECT Id FROM dbo.Split(@DelStr,'|'))


I am using Entity Framework with C# to make a Silverlight application. I have written some stored procedures which perform database intensive operations and I need to call them from Entity Framework after passing some parameters. In one of the steps, the users select a list of items for which they would need more details. This list of items (in the form of an array of integer IDs) need to be passed to the stored procedure to retrieve more information about those IDs. How do I pass this parameter to the stored procedure?

解决方案

You can't pass table-valued parameters to SQL with the Entity Framework.

What you can do is create a delimited string like "1|2|3|4" and create a Split function in SQL that will return a table.

CREATE FUNCTION dbo.Split
(
    @RowData nvarchar(2000),
@SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
Id int identity(1,1),
Data nvarchar(100)
) 
AS  
BEGIN 
Declare @Cnt int
Set @Cnt = 1

While (Charindex(@SplitOn,@RowData)>0)
Begin
    Insert Into @RtnValue (data)
    Select 
        Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

    Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
    Set @Cnt = @Cnt + 1
End

Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))

Return
END

Then if you need to do something like select all items from a table based on what is in the delimited string passed to your proc:

SELECT * FROM SomeTable WHERE Id IN (SELECT Id FROM dbo.Split(@DelStr, '|'))

这篇关于通过实体框架将数组/表传递给存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆