Passing table-valued parameters to stored procedures in Entity Framework
Entity Framework itself does not natively support passing table-valued parameters directly to stored procedures. However, this can be achieved by using the ObjectContext
command with ExecuteStoreQuery
.
Create a universal warehousing method
First, define a general warehousing method:
<code class="language-csharp">public IEnumerable<T> ExecuteStoredProcedure<T>(string procedureName, params object[] parameters) { // 构建命令字符串 StringBuilder command = new StringBuilder(); command.Append("EXEC "); command.Append(procedureName); command.Append(" "); // 添加参数占位符 for (int i = 0; i < parameters.Length; i++) { if (i > 0) command.Append(","); command.Append("{" + i + "}"); } // 执行查询 return this.context.ExecuteStoreQuery<T>(command.ToString(), parameters); }</code>
Use ExecuteStoreQuery with table-valued parameters
When using ExecuteStoreQuery
with table-valued parameters, set the SqlParameter
attribute of SqlDbType
to Structured
and the TypeName
attribute to the name of the user-defined type:
<code class="language-csharp">var warnings = new SqlParameter("warnings", SqlDbType.Structured); warnings.Value = dt; warnings.TypeName = "dbo.udt_Warnings";</code>
Pass parameters to stored procedure
In the ExecuteStoredProcedure
method, make sure the parameters are passed in the correct order:
<code class="language-csharp">entities.ExecuteStoredProcedure("usp_RaiseWarnings_rs", userId, warnings, caseId);</code>
DbContext and ObjectContext
For Entity Framework Code First, DbContext
needs to be converted to ObjectContext
to use the ExecuteStoreQuery
method:
<code class="language-csharp">var entities = (ObjectContext)context; entities.ExecuteStoredProcedure("usp_RaiseWarnings_rs", userId, warnings, caseId);</code>
Additional Notes
ExecuteStoreCommand
must be in the same order as in the stored procedure. The above is the detailed content of How Can I Pass Table-Valued Parameters to Stored Procedures in Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!