Entityframework Executesqlcommand not accepting parameter

Asked

Viewed 91 times

2

I’m running the Executesqlcommand.

In the right way, parameter doesn’t work:

var SQL = "update POSTOFFICE set Status = 1 where name = '@url'";
dbMailEnable.Database.ExecuteSqlCommand(SQL, new SqlParameter("@url", EP.Cliente.Url.Trim().ToLower()));

Parameter-less works!

var SQL = "update POSTOFFICE set Status = 1 where name = '" + EP.Cliente.Url.Trim().ToLower() + "'";
dbMailEnable.Database.ExecuteSqlCommand(SQL);

But without parameter is not recommended, SQL Injection, etc. alias in Visual Studio help nor it was possible.

What to do?

NOTE: I’m having to use this command because the database is of third party and has no primary key so I could not do via Model.

  • try to do var param = EP.Cliente.Url.Trim().ToLower(); dbMailEnable.Database.ExecuteSqlCommand(SQL, new SqlParameter("@url",param);

  • 1

    I can direct a second response using the Database and not the Connection, but I need details of the error.

1 answer

4

If the idea is to use as ADO.NET, you can get the DbConnection of context and execute the command using SqlParameters normally:

using (var connection = dbMailEnable.Database.Connection as SqlConnection) // Não tem problema ~neste caso~ porque o Entity Framework garante uma SqlConnection pra você. 
{
    var command = new SqlCommand("update POSTOFFICE set Status = 1 where name = '@url'", connection);
    command.Parameters.Add(new SqlParameter("@url", EP.Cliente.Url.Trim().ToLower()));
    var registrosAfetados = command.ExecuteNonQuery();
}
  • Is there any advantage? it’s faster?

  • 1

    It’s almost the same thing. It has the advantage that you have total control over what you’re running, as it is in ADO.NET.

  • cannont Convert from 'System.Data.Common.Dbconnection' to 'System.Data.Sqlclient.Sqlconnection'

  • 1

    I updated the answer. I missed the cast.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.