动态 Sql 语句由方法 Up 中的变量更改

Dynamic Sql statement change by variable in method Up

我想使用代码优先迁移将值插入 PostgreSql table。 到目前为止我的代码:

public override void Up()
{
    var test = "TestValue";
    Sql(@"Insert into dbo.""Company"" (""Id"", ""Name"") values ('2', test)");
}

这是示例代码。我想要实现的是将预先计算的值插入 Name 列。上面的代码将失败并显示 there is no column named test 消息,但我的意图是替换 test 的值。请用正确的语法帮助我。

您有 2 种可能性,要么使用 string concatenation or the String.Format. If you need formatted output e.g. number of decimals in a number etc. then you should use String.Format

String concatenation:

var test = "TestValue";
string sqlString = @"Insert into dbo.""Company"" (""Id"", ""Name"") values ('2', '" + test + @"')";
Sql(sqlString);

String.Format:

var test = "TestValue";
string sqlString = string.Format(@"Insert into dbo.""Company"" (""Id"", ""Name"") values ('2', '{0}')", test);
Sql(sqlString);

您的 sqlString 将包含:
Insert into dbo."Company" ("Id", "Name") values ('2', 'TestValue') 之后。

            SqlCommand cmd = new SqlCommand();
            SqlDataReader reader;
            var test = "Test";
            cmd.CommandText = "Insert INTO yourTableName (Id,Name) VLAUES ('2' ," + test + ")"; 
            cmd.CommandType = CommandType.Text;

            reader = cmd.ExecuteReader();