我正在尝试使用字符串变量的内容来检查数据库中是否存在记录。我发送方法2参数。这是接收方法:
public Boolean recordExists(String targetTable, String data)
{
//a bunch of Table connections strings are here, example:
Table<Road> Roads = db.GetTable<Road>();
//check if the record exists in the table (an integer in this case)
var roadQuery = from id in targetTable where id.ID == Convert.ToInt32(data) select id;
}
例如,'targetTable'的值可能是“Roads”,我想查看值'data'是否存在于数据库中Roads表的ID字段中。如何创建动态LINQ查询来执行此操作?
答案 0 :(得分:2)
这是简单的兄弟:
public bool recordExists(String targetTable, string fieldName, String data)
{
return (bool)(db.ExecuteQuery<int>("SELECT COUNT(*) FROM [{0}] WHERE [{1}] = '{2}'",
targetTable, fieldName, data).Single() > 0);
}
注意:SQL中的单引号工作甚至字段是数字。
答案 1 :(得分:0)
也许是这样的:
public bool recordExists(String targetTable, string fieldName, String data)
{
return db.ExecuteQuery<bool>(string.Format(@"SELECT
CASE WHEN EXISTS(SELECT NULL FROM [{0}] WHERE [{1}]='{2}')
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT)
END",targetTable,fieldName,data));
}