Can Entity Framework Core run non-query calls?

c# entity-framework entity-framework-core

Question

Unfortunately my EF application has to call stored procedures I am unable to change. While this is not ideal I can normally get around it. However, I have a stored proc that does return anything. How does EF core deal with this? I know in previous versions you could run ExecuteNonQuery but I haven't been able to find anything similar in EF Core.

I normally run my queries through a helper as such, where T is a class that maps to a return type EF can serialize to:

context.Set<T>()
.AsNoTracking()
.FromSql(query, args)
.ToListAsync();

However it looks like Set always requires a type as does .Query. Nothing else I've seen off of context would allow you to make a non-queryable call. Am I missing something?

I am using Microsoft.EntityFrameworkCore: 1.2.0

1
4
2/17/2017 9:50:42 PM

Accepted Answer

You can use the DbContext.DatabaseExecuteSqlCommand method

using(var context = new SampleContext())
{
    var commandText = "INSERT Categories (CategoryName) VALUES (@CategoryName)";
    var name = new SqlParameter("@CategoryName", "Test");
    context.Database.ExecuteSqlCommand(commandText, name);
} 

Or you can revert to ADO.NET calls off the Context:

using (var context = new SampleContext())
using (var command = context.Database.GetDbConnection().CreateCommand())
{
    command.CommandText = "DELETE From Table1";
    context.Database.OpenConnection();
    command.ExecuteNonQuery();
}
7
2/18/2017 9:20:08 PM


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