Using SQL Table valued parameter with Entity Framework

后端 未结 1 1005
天命终不由人
天命终不由人 2021-01-07 04:20

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 manipulation

1条回答
  •  攒了一身酷
    2021-01-07 04:42

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

    Example:

    // Create metadata records
    IEnumerable sqlDataRecords = new List();
    
    // 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();
    }
    

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