【问题标题】:Can Entity Framework Core run non-query calls?Entity Framework Core 可以运行非查询调用吗?
【发布时间】:2017-02-19 05:20:08
【问题描述】:

不幸的是,我的 EF 应用程序必须调用我无法更改的存储过程。虽然这并不理想,但我通常可以绕过它。但是,我有一个确实返回任何内容的存储过程。 EF 核心如何处理这个问题?我知道在以前的版本中您可以运行 ExecuteNonQuery,但我无法在 EF Core 中找到类似的东西。

我通常通过一个帮助器来运行我的查询,其中 T 是一个映射到返回类型的类 EF 可以序列化为:

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

但是看起来 Set 和 .Query 一样总是需要一个类型。我在上下文中看到的任何其他内容都不会允许您进行不可查询的调用。我错过了什么吗?

我正在使用 Microsoft.EntityFrameworkCore:1.2.0

【问题讨论】:

    标签: c# entity-framework entity-framework-core


    【解决方案1】:

    您可以使用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);
    } 
    

    或者你可以回复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();
    }
    

    【讨论】:

    • 我明白了。谢谢你。我需要将 Microsoft.EntityFrameworkCore.Relational 包添加到我的项目中才能使其正常工作。
    • 我上面概述的方法不依赖于 Microsoft.EntityFrameworkCore.Relational。您一定在项目中需要它来做其他事情。
    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 2022-01-25
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多