What is the correct syntax for using Database.ExecuteSqlCommand with parameters?

entity-framework sql sql-server

Question

I want to call a stored method with input parameters using Entity Framework 4.2. I useDatabase.ExecuteSqlCommand to invoke the stored command.

The proper call syntax, nevertheless, is missing from the documentation in order to properly translate the arguments. I need assistance because my google-foo isn't working.

I.e. I must follow a process.

procedure SetElementFrequency
  @ElementTypeID integer,
  @Frequency float
as ...

I've attempted to call it with

Database.ExecuteSqlCommand("exec SetElementFrequency @p0 @p1", 
                            elementType, frequency);

and

Database.ExecuteSqlCommand("exec SetElementFrequency {0} {1}", 
                            elementType, frequency);

nonetheless, they both make the mistake Uncorrected syntax close to "@p1"..

1
10
3/1/2013 7:34:36 AM

Accepted Answer

You may use one of the following methods, depending on the underlying database supplier.

Database.ExecuteSqlCommand(
    "exec SetElementFrequency {0}, {1}",
    elementType, frequency); 

or

Database.ExecuteSqlCommand("exec SetElementFrequency ?, ?", elementType, frequency); 

You may add details.elementType and frequency by using the ParameterName attribute to offer your own names as DbParameter-based objects.

16
6/5/2013 5:08:45 PM

Popular Answer

var sql = @"Update [User] SET FirstName = {0} WHERE Id = {1}";
ctx.Database.ExecuteSqlCommand(sql, firstName, id);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow