Using SQL Table valued parameter with Entity Framework

谁说胖子不能爱 提交于 2019-12-09 01:24:57

问题


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:


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();
}


来源:https://stackoverflow.com/questions/19545835/using-sql-table-valued-parameter-with-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!