1

I am using Core 2.0 using entity framework. I have successfully generated context using scaffold DBContext. I have DBSet for table EMployee. I need to execute SToredProcedure which will give list of employee. I cannot see .FromSql nor.ExecuteCommand option.

I have added EntityFrameworkCore.SqlServer(2.0.1),EntityFrameworkCore.SqlServer.Design(1.1.5),Microsoft.VisualStudio.Web.CodeGeneration.Design(2.0.2) and EntityFrameworkCore.Tools(2.0.1) but to no awail.

Please guide for mentioned concerns.

3
  • What have you tried so far? What have you searched for, too? I searched "ef core call stored procedure" in Google and got many, many results (most of which are questions here with accepted answers) Commented Feb 9, 2018 at 13:26
  • 4
    Possible duplicate of How to run stored procedures in Entity Framework Core? Commented Feb 9, 2018 at 13:53
  • I am not able to get intellisense for FromSql method Commented Feb 10, 2018 at 4:36

2 Answers 2

2

If you want to execute row SQL using EF Core, try the following.

var employees = context.Employees
.FromSql("SELECT * FROM dbo.Employees")
// If you want to execute a stored procedure, then below
// .FromSql("EXECUTE {SP_NAME}")
.ToList();

But note, there are certain limitations present as described here: https://learn.microsoft.com/en-us/ef/core/querying/raw-sql#limitations

Sign up to request clarification or add additional context in comments.

Comments

1

This is the only way to execute Raw SQL in .NET at the moment:

var conn = _context.Database.GetDbConnection();
try
{
    await conn.OpenAsync();
    using (var command = conn.CreateCommand())
    {
        command.CommandText = "SELECT * From Table1 WHERE sender = @sender";
        DbParameter sender = command.CreateParameter();
        sender.ParameterName = "sender";
        sender.Value = "Value";
        command.Parameters.Add(sender);
        DbDataReader reader = await command.ExecuteReaderAsync();

        if (reader.HasRows)
        {
            while (await reader.ReadAsync())
            {
                int SubscriptionID = reader.GetInt32(0);
            }
        }
        reader.Dispose();
    }
}
finally { conn.Close(); }

You can use it for stored procedures as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.