简体   繁体   English

如何在 Dapper 中插入 SQL 文字作为查询参数?

[英]How to insert an SQL literal as a query parameter in Dapper?

I want to insert part of SQL statement as a parameter instead of concatenation to have it neat:我想插入 SQL 语句的一部分作为参数而不是串联以使其整洁:

connection.Query(@"
    SELECT @Fields
    FROM Table
    WHERE ID = @Id
    ", new { Fields = "A, B", Id = 1});

I tried wrapping the parameter string in a custom class and mapping the class using Dapper我尝试将参数字符串包装在自定义类中并使用 Dapper 映射该类

public class SqlString
{
    public readonly string Value;

    public SqlString(string sql)
    {
        Value = sql;
    }

    public override string ToString()
    {
        return Value;
    }
}

...

Dapper.SqlMapper.AddTypeMap(typeof(SqlString), System.Data.DbType.Object);

but to no avail.但无济于事。

You can't parameterize field names in T-SQL.您不能在 T-SQL 中参数化字段名称。

You will have to generate the dynamic SQL with your dynamic field names before you pass the sql string into the Connection.Query() method.在将 sql 字符串传递到Connection.Query()方法之前,您必须使用动态字段名称生成动态 SQL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM