如何在一个查询中将所有 C# 对象值插入到 MySQL table?

How to insert all C# object values to MySQL table in one query?

我有一个带有很多参数的对象,每个参数代表MySQLtable中的一列。

我有一个代码可以生成一个包含上述所有参数及其值的新对象:

foreach (MetaData metaData in elnetMcMapping.DataItems) {
    var value = metaData.Value[0] * metaData.Multiplier;
    Type type = mcReadings.GetType();
    PropertyInfo prop = type.GetProperty(metaData.Label);
    prop.SetValue(mcReadings, value, null);
}

现在我想将所有值作为新行插入 MySql table 但不确定如何动态实现以下逻辑:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

我正在寻找这样的东西:

await dataAccess.SaveData("insert into", mcReadings, DeviceDb);

有人有代码示例可以帮助我解决这个问题吗?

var propList = mcReadings.GetType().GetProperties().ToList();
StringBuilder str = new StringBuilder();
str.Append("INSERT INTO elnet21630388 (");
foreach(PropertyInfo prop in propList) {str.Append(prop.Name + ",");}
str.Remove(str.Length - 1, 1);
str.Append(") VALUES (");
foreach (PropertyInfo prop in propList) { str.Append(prop.GetValue(mcReadings).ToString() + ","); }
str.Remove(str.Length - 1, 1);
str.Append(");");

我做了如下操作:

// Build the SQL statement, this can be cached and used again
var propList = mcReadings.GetType().GetProperties().ToList();
StringBuilder str = new StringBuilder();
str.Append("INSERT INTO elnet21630388 (");
// Build column list
foreach(PropertyInfo prop in propList) 
{
    str.Append(prop.Name + ",");
}
str.Remove(str.Length - 1, 1);
str.Append(") VALUES (");
// Build values list
foreach (PropertyInfo prop in propList) 
{ 
    str.Append("@" + prop.Name + ",");
}
str.Remove(str.Length - 1, 1);
str.Append(");");

// Generate the dynamic parameters, this needs to be done on each call 
DynamicParameters parameters = new DynamicParameters();
foreach (PropertyInfo prop in propList)
{
    parameters.Add("@" + prop.Name, prop.GetValue(mcReadings, null));
}

connection.Execute(str.ToString(), parameters);