c# - Linq to sql .Dynamic 其中:带有 System.Linq.Dynamic.ParseException 的字符串:“myTable”类型中不存在属性或字段“0”
问题描述
我正在尝试对 myTables 之一进行动态查询
为此,我使用以下功能:
public async Task<bool> search(DBContext db, M model, string uniqueNonIDField)
{
Type modelType = model.GetType();//get model of generic
object modelInstance = Activator.CreateInstance(modelType);
PropertyInfo field = modelType.GetProperty(uniqueNonIDField); //get property to get existing value
if (field == null)
throw new Exception(string.Format("Campo {0} Não encontrado", uniqueNonIDField));
string value = (string)field.GetValue(model, null); //get value to search in myTable
field.SetValue(model, Regex.Replace(value, @"[\u002D\u2010\u2012\u2013\u2014]", "-"), null); //do some clean up
value = (string)field.GetValue(model, null); //get new value after being cleaned
if (db.Set(modelType).Where(String.Format("@0=@1", uniqueNonIDField, value)).Count() == 0) //Test if there is already any object in myTable with that value.
{...do stuff}
...
}
但是有一个错误:
System.Linq.Dynamic.ParseException: No property or field '0' exists in type 'myTable'
如果我对所有表达式进行硬编码,例如:
if (db.myTable.Where("existingField=123").Count() == 0){...}
错误仍然存在:
System.Linq.Dynamic.ParseException: No property or field '123' exists in type 'myTable'
我正在尝试按照许多示例中的示例进行操作,并看到了许多其他 stackoverflow 类似的答案,但找不到错误的原因。可能是菜鸟的错误。
你能帮我找到它吗?
解决方案
您可以将字符串传递给 where 语句。System.Linq.Dynamic
允许您按字符串过滤。
您的代码似乎一切正常,也许您的问题与此有关: https ://github.com/zzzprojects/System.Linq.Dynamic/issues/101
您是否在 dotnetcore 下使用此代码?如果是,请安装相关的 NuGet 包并将使用更改为System.Linq.Dynamic.Core
推荐阅读
- ffmpeg - 将视频分成几部分
- java - 如何使用 Java 中的 RestFB 发布到 Instagram?
- neo4j - Neo4j - 图形空值
- git - Git:如何在不区分大小写的文件系统上签出分支?Git 认为我在工作树中有未跟踪的文件,而我没有
- minecraft - 如何在我的世界 1.14 中使用命令块设置交易箱?
- prolog - 从包含的 prolog 文件访问谓词
- java - 如何遍历二叉树
- elasticsearch - 如何为一条数据中的值数量创建脚本字段?
- amazon-web-services - AWS sam 对远程资源的本地调用
- python - 有没有比 csv.DictReader 更好的方法来编译来自多个文件的列数据?