Passing an array/table to stored procedure through Entity Framework

后端 未结 3 1520
说谎
说谎 2021-02-20 03:30

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

相关标签:
3条回答
  • 2021-02-20 04:02

    Is this what you were looking for?

    0 讨论(0)
  • 2021-02-20 04:07

    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, '|'))
    
    0 讨论(0)
  • 2021-02-20 04:16

    If you are using SQL Server, which I assume is the case, you can create use a table valued parameter to do what you wish. Using a table valued parameter prevents you from parsing an input parameter within the stored procedure and removes the threat of a SQL injection attack by eliminating the use of dynamic SQL.

    Here is a great blog article that covers how to do what you wish to do.

    Using Table-Valued Parameters in SQL Server 2008 and C#

    0 讨论(0)
提交回复
热议问题