【问题标题】:Get value from sql select if parameter may be null如果参数可能为空,则从 sql 选择中获取值
【发布时间】:2021-01-16 21:02:17
【问题描述】:

寻找一种方法,使用 EF Core 从 ASP.NET MVC Core 应用程序中的任意 sql 查询中获取第一列中第一行的值。

喜欢

   var total = ctx.ExecuteScalar<decimal?>(@"select ... where p1={0}", null);

使用 Npgsql EF Provider 尝试了来自 https://github.com/dotnet/EntityFramework.Docs/issues/969https://github.com/weitzhandler 代码(更改为同步):

public partial class EevaContext : DbContext
{   
    public T ExecuteScalar<T>(string rawSql, params object[] parameters)
    {  
        var context = this;
        var conn = context.Database.GetDbConnection();
        using var command = conn.CreateCommand();
        command.CommandText = rawSql;
        if (parameters != null)
            foreach (var p in parameters)
                command.Parameters.Add(p ?? DbNull.Value);
        conn.Open();
        return (T)command.ExecuteScalar();
    }

如果参数值为空行

command.Parameters.Add(p ?? DbNull.Value);

抛出错误

InvalidCastException:值“”不是“NpgsqlParameter”类型 并且不能在此参数集合中使用。 Npgsql.NpgsqlParameterCollection.Cast(对象值)

运行此类查询的最佳方式是什么? 也许 EF 核心有一些内置方法?还是使用某种类型并将其注入 EF Context is OnModelCreated 方法更好?

如果没有更好的方法来修复此代码,以便也接受具有空值的参数?

在应用程序中有很多这样的查询,其中包含很多参数,并且在大量工作中重新查询所有这些查询。 .NET 4 中使用了 WebMatrix QueryValue,它允许在参数中使用空值。

【问题讨论】:

    标签: entity-framework entity-framework-core ado.net npgsql executescalar


    【解决方案1】:

    command.Parameters.Add(p ?? DbNull.Value);

    p 是 NpgsqlParameter,还是您要发送的某个值?您不能简单地将值(或 null)添加到 command.Parameters.Add - 您需要使用 NpgsqlParameter 包装这些值或使用 command.Parameters.AddWithValue() 代替。请注意,NpgsqlParameter 还需要正确设置其 ParameterName,对应于原始 SQL 中的占位符(例如 @param1)。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      • 2014-08-06
      • 1970-01-01
      相关资源
      最近更新 更多