【问题标题】:Cannot execute Raw Sql in .Net COre无法在 .Net COre 中执行 Raw Sql
【发布时间】:2018-02-10 01:30:01
【问题描述】:

我正在使用使用实体框架的 Core 2.0。 我已经使用脚手架 DBContext 成功生成了上下文。 我有表 EMployee 的 DBSet。 我需要执行 SToredProcedure,它会给出员工名单。 我看不到 .FromSql 和 .ExecuteCommand 选项。

我添加了 EntityFrameworkCore.SqlServer(2.0.1)、EntityFrameworkCore.SqlServer.Design(1.1.5)、Microsoft.VisualStudio.Web.CodeGeneration.Design(2.0.2) 和 EntityFrameworkCore.Tools(2.0.1) 但是没办法。

请指导提到的问题。

【问题讨论】:

  • 到目前为止您尝试过什么?你也搜索过什么?我在 Google 中搜索了“ef core call stored procedure”,得到了很多很多的结果(其中大部分是这里的问题,有公认的答案)
  • 我无法获得 FromSql 方法的智能感知

标签: .net-core entity-framework-core


【解决方案1】:

如果要使用 EF Core 执行行 SQL,请尝试以下操作。

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

但请注意,此处所述存在某些限制: https://docs.microsoft.com/en-us/ef/core/querying/raw-sql#limitations

【讨论】:

    【解决方案2】:

    这是目前在 .NET 中执行 Raw SQL 的唯一方法:

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

    您也可以将它用于存储过程。

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 2021-07-15
      • 2022-08-23
      • 2022-10-06
      • 2019-11-23
      • 2019-10-03
      • 2015-05-07
      • 2020-12-23
      • 1970-01-01
      相关资源
      最近更新 更多