Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to DbMigration.Sql() Method

When using Entity Framework Migrations, the DbMigration base class has a Sql method which takes parameters in an anonymous object

I cannot for the life of me figure out how to use it.

        Sql(@"
                UPDATE dbo.SlideSets 
                SET Name = @Name, 
            ", false, new {
                Name = "Foo"
            }
        );

Results in the error

System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@Name"

What's the correct syntax of this statement?

like image 328
George Mauer Avatar asked Nov 17 '13 18:11

George Mauer


People also ask

Can We pass parameters to a view in SQL Server?

No, in SQL Server, we cannot pass parameters to a view. And it can be considered as one main limitation of using a view in SQL Server. Moreover, even if we try to pass parameters to a view, the SQL Server will return an error. Let’s understand this limitation using an example in SQL Server. For this example, consider the following SQL query.

How to assign passed parameters to a specific variable in SQL Server?

However, if you want to assign your passed parameters to specific variable inside SQL Server, you will have to mention that parameter as mentioned in the second method. In this method when we execute the stored procedure, we also include the variable to which we want to assign parameter.

Is it possible to pass named parameters to executesqlcommand?

The following example (not my real example) doesn't work. The ExecuteSqlCommand method doesn't allow you to pass in named parameters like in ADO.Net and the documentation for this method doesn't give any examples on how to execute a parameterized query.

Is it better to use LINQ or dbmigration?

Using LINQ is better, even for usual migrations, because, there is a bug in DbMigration.Sql method, it ignores arguments: How to pass parameters to DbMigration.Sql () Method Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.


2 Answers

I dug into the EF source code and it seems that this parameter (or rather the MigrationOperation.AnonymousObject property that's created from it) is not used at all!

I've created a ticket on their issue tracker to either do something about it or remove the api

like image 159
George Mauer Avatar answered Oct 12 '22 09:10

George Mauer


The standard generator for MSSQL is doing nothing with the anonymous object in this case. You need to put the parameter directly into command. Or you can derive your own and handle it.

like image 45
cincura.net Avatar answered Oct 12 '22 09:10

cincura.net