C# 对具有字符串字段的数据库的查询
我可以在数据库中查询字符串中的字段吗C# 对具有字符串字段的数据库的查询,c#,linq,C#,Linq,我可以在数据库中查询字符串中的字段吗 string fieldName = "Column1"; SQL: 我需要使用LINQ 对于这些问题,是否有一些内置的、快速的解决方法,或者思考是否起到了作用?试试这个: 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
string fieldName = "Column1";
SQL:
我需要使用LINQ
对于这些问题,是否有一些内置的、快速的解决方法,或者思考是否起到了作用?试试这个:
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();
}
您可以为此实现一个简单的方法:
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;
}
}
}
}
您希望Linq语句看起来像什么?使用原始SQL命令:
var values=context.Database.SqlQuery(SQL.ToArray()
@mm8 I have error“DatabaseFacade”不包含“ExecuteQuery”的定义,并且找不到接受“DatabaseFacade”类型的第一个参数的可访问扩展方法“ExecuteQuery”(是否缺少using指令或程序集引用?
)。所以它没有work@startNet:您无法在测试中对DatabaseFacade
执行原始查询。Select(x=>x.fieldName)
执行与Select I.fieldName
相同的操作。这将只返回字符串集合,其中每个字符串都将是字段的名称。@LasseVågsætherKarlsen我更改了答案var fieldName=“1;DROP TABLE myTable;”代码>。我认为值得在您的答案中添加一点,即SQL注入是可能的here@AleksAndreev:sql注入是当用户可以注入他/她自己的sql时,典型的反模式是stringSQL=$“从MyTable中选择{Edit1.Text}”代码>;在本例中,Edit1.Text
可以很好地包含MyTable中的123;删除MyTable--
并销毁数据库。然而,在我的解决方案中,sql
是一个本地变量,用户无法更改它ReadSqlRecords
是一种private
方法(因此不能从外部错误调用)。您说得很对,我们不应该允许用户运行任意查询,如…ReadSqlRecords(Edit1.Text).
,但这是一个不同的警告。
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();