Can Entity Framework Core run non-query calls?

孤者浪人 提交于 2020-07-05 10:26:57

问题


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:


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();
}


来源:https://stackoverflow.com/questions/42308010/can-entity-framework-core-run-non-query-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!