Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes "Incorrect syntax near <stored procedure name>" in EF Code First and SQL 2005?

The examples for System.Data.Entity.Database.SqlQuery method I've found appear to work well with SQL 2008 R2 but do not appear to work with SQL 2005.

This call will work with SQL 2008 R2:

var myEntities = dbContext.Database.SqlQuery<MyEntity>("GetDataFromMySp @EntityId = {0}", entityId);

However, in SQL 2005 this statement will throw a SqlException with an error message of "Incorrect syntax near 'GetDataFromMySp'".

like image 325
Dan Mork Avatar asked Jun 19 '11 17:06

Dan Mork


People also ask

How do you resolve Incorrect syntax near?

You can try to directly run your query to database and check if syntax is correct. There can be multiple () where your query might be failing. For example in my case the argument passed for IN clause was empty creating my query something like select * from tableName where id in () and hence was getting error.

What does Incorrect syntax near mean in SQL?

When executing a query in SQL and the editor throws back this error: Incorrect syntax near …'' That typically means you have used the wrong syntax for the query. This happens mostly when someone switched from one relational database to another relational database, from MySQL to MS SQL Server for example.

Does EF allow calling stored procedure?

The Entity Framework has the capability of importing a Stored Procedure as a function. We can also map the result of the function back to any entity type or complex type.

What is EF in SQL?

Entity Framework Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations. EF Core works with many databases, including SQL Database (on-premises and Azure), SQLite, MySQL, PostgreSQL, and Azure Cosmos DB.


1 Answers

Solution found by @Dan himself (couldn't post due to rep)

The solution I found to this issue was simply to add the keyword "EXEC" to the query:

var myEntities = dbContext.Database.SqlQuery<MyEntity>("EXEC GetDataFromMySp @EntityId = {0}", entityId);

This solution fixed the issue with SQL Server 2005 and still worked with SQL Server 2008 R2.

like image 156
PedroC88 Avatar answered Sep 21 '22 16:09

PedroC88