2

I am using Entity Framework v4.0 in my project to connect to a database. I am in a situation to pass a List as input parameter to a stored procedure and do some manipulations in SP and get back List as SP result. I know table valued parameter is one option. But after some investigation I found it is not possible to use Table Valued parameter in Entity Framework. Is there any other way without using Table Valued Parameter to do it through Entity framework?

1
  • Is there any chance you could upgrade to EF5? It is supported Commented Oct 23, 2013 at 15:33

1 Answer 1

5

You can still pass a TVP to a stored procedure even if you are using entity framework.

Example:

// Create metadata records
IEnumerable<SqlDataRecord> sqlDataRecords = new List<SqlDataRecord>();

// Create a list of SqlDataRecord objects from your list of entities here

SqlConnection storeConnection = (SqlConnection)((EntityConnection)ObjectContext.Connection).StoreConnection;
try
{
    using (SqlCommand command = storeConnection.CreateCommand())
    {
        command.Connection = storeConnection;
        storeConnection.Open();

        SqlParameter[] sqlParameters = parameters.ToArray();
        command.CommandText = YourStoredProcedureName;
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("YourTVPName", SqlDbType.Structured)
                            {
                                Value = sqlDataRecords,
                                TypeName = "dbo.Your_Table_Type"
                            });

        using (DbDataReader reader = command.ExecuteReader())
        {
            // Read results
        }
    }
}
finally
{
    storeConnection.Close();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thankssss!!!! That helps.... But how to get back the list from Stored Procedure ?? ExecuteReader does it ??
See here for info on reading the results: msdn.microsoft.com/en-us/library/haa3afyz.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.