我能以某种方式在数据库中查询我在字符串中的字段吗?
string fieldName = "Column1";SQL:
string sql = "SELECT " + fieldName + " FROM myTable";我需要使用LINQ来完成此操作
对于这样的问题,有没有什么内置的、快速的东西,或者思考是否起到了作用?
发布于 2019-09-04 18:09:50
为此,您可以实现一个简单的方法:
private static IEnumerable<IDataRecord> ReadSqlRecords(string sql) {
//TODO: Put connection string here
//TODO: I've assumed you work with MS SQL; if not replace SqlConnection
using (var conn = new SqlConnection("ConnectionStringHere")) {
conn.Open();
using (var q = conn.CreateCommand()) {
q.CommandText = sql;
using (var reader = q.ExecuteReader()) {
while (reader.Read())
yield return reader;
}
}
}
}然后你就可以使用它了
string sql = $"SELECT {fieldName} FROM myTable";
// Now you can put Linq
var result = ReadSqlRecords(sql)
.Where(record => Convert.ToInt32(record["Id"]) > 100)
.Count();发布于 2019-09-04 17:56:31
试试这个:
using (var context = new MyContext())
{
// Get the object from the table (in this case I give an example to get the first row. You can use Where for the condition)
var row = context.MyTable.FirstOrDefault();
// Get the field value with reflection
response = row.GetType().GetProperty(name).GetValue(row, null).ToString();
}https://stackoverflow.com/questions/57785664
复制相似问题