Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Entity Framework Core run non-query calls?

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

like image 777
evenflow58 Avatar asked Feb 17 '17 21:02

evenflow58


People also ask

What's new in queries in Entity Framework Core?

Here, you will learn the new features of querying introduced in Entity Framework Core. EF Core has a new feature in LINQ-to-Entities where we can include C# or VB.NET functions in the query. This was not possible in EF 6.

Is it possible to run executenonquery in EF Core?

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:

What is Entity Framework no-tracking queries?

No-Tracking Queries Tracking behavior controls if Entity Framework Core will keep information about an entity instance in its change tracker. If an entity is tracked, any changes detected in the entity will be persisted to the database during SaveChanges ().

How does EF Core handle tracking query results?

When the results are returned in a tracking query, EF Core will check if the entity is already in the context. If EF Core finds an existing entity, then the same instance is returned. EF Core won't overwrite current and original values of the entity's properties in the entry with the database values.


1 Answers

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();
}
like image 102
Mike Brind Avatar answered Oct 13 '22 05:10

Mike Brind