Home >Database >Mysql Tutorial >How to Use DbContext.Database.SqlQuery with Stored Procedures and Parameters in EF Code First CTP5?

How to Use DbContext.Database.SqlQuery with Stored Procedures and Parameters in EF Code First CTP5?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-17 11:57:09224browse

How to Use DbContext.Database.SqlQuery with Stored Procedures and Parameters in EF Code First CTP5?

Use DbContext.Database.SqlQuery to call stored procedures in Entity Framework Code First CTP5

The

Entity Framework Code First CTP5's DbContext.Database.SqlQuery<TElement>(sql, params) method allows calling a stored procedure and retrieving the results as a list of TElement type objects. However, if the stored procedure requires parameters, they must be specified in the call to SqlQuery.

SqlParameter parameter

When providing a SqlParameter object as a parameter, the parameter name must be included in the SQL query and preceded by the @ symbol. For example, for a stored procedure that requires three parameters, you would specify the following query:

<code class="language-sql">"mySpName @param1, @param2, @param3"</code>

You will then create three SqlParameter objects and pass them to SqlQuery like this:

<code class="language-csharp">context.Database.SqlQuery<MyEntityType>(
    "mySpName @param1, @param2, @param3",
    new SqlParameter("param1", param1),
    new SqlParameter("param2", param2),
    new SqlParameter("param3", param3)
);</code>

Note that the parameter names in the SqlParameter object must match the parameter names in the stored procedure.

The above is the detailed content of How to Use DbContext.Database.SqlQuery with Stored Procedures and Parameters in EF Code First CTP5?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn