Search code examples
entity-frameworkstored-proceduresbulkinserttable-valued-parameters

EntityFrameWork and TableValued Parameter


I'm trying to call a stored procedure from EntityFramework which uses Table-value parameter.

But when I try to do function import I keep getting a warning message saying -

The function 'InsertPerson' has a parameter 'InsertPerson_TVP' at parameter index 0 that has a data type 'table type' which is currently not supported for the target .NET Framework version. The function was excluded.

I did a initial search here and found few posts which says It's possible in EntityFrameWork with some work arounds and few saying it's not supported in current versions.

Does any one know a better approach or solution for this problem?


Solution

  • I ended up doing this, Please note we are working on EF DataContext(not ObjectContext)

    Executing a Stored procedure with output parameter

           using (DataContext context = new DataContext())
            {                  
              ////Create table value parameter
              DataTable dt = new DataTable();
              dt.Columns.Add("Displayname");
              dt.Columns.Add("FirstName");
              dt.Columns.Add("LastName");
              dt.Columns.Add("TimeStamp");
    
              DataRow dr = dt.NewRow();
              dr["Displayname"] = "DisplayName";
              dr["FirstName"] = "FirstName";
              dr["LastName"] ="LastName";
              dr["TimeStamp"] = "TimeStamp";             
              dt.Rows.Add(dr);
    
              ////Use DbType.Structured for TVP
              var userdetails = new SqlParameter("UserDetails", SqlDbType.Structured);
              userdetails.Value = dt;
              userdetails.TypeName = "UserType";
    
              ////Parameter for SP output
              var result = new SqlParameter("ResultList", SqlDbType.NVarChar, 4000);
              result.Direction = ParameterDirection.Output;
    
              context.Database.ExecuteSqlCommand("EXEC UserImport @UserDetails, @ResultList OUTPUT", userdetails, result);
    
              return result == null ? string.Empty : result.Value.ToString();
            }
    

    My Table-Value-Parameter (UDT Table) script looks like this:

    CREATE TYPE [dbo].[UserType] AS TABLE (
        [DisplayName]      NVARCHAR (256)   NULL,
        [FirstName]        NVARCHAR (256)   NULL,
        [LastName]         NVARCHAR (256)   NULL,
        [TimeStamp]        DATETIME         NULL
       )
    

    And my store procedure begins like

    CREATE PROCEDURE UserImport 
    -- Add the parameters for the stored procedure here
    @UserDetails UserType Readonly,
    @ResultList NVARCHAR(MAX) output  
    AS
    

    For Stored procedure without output parameter we don't need any ouput parameter added/passed to SP.

    Hope it helps some one.