首页 > 解决方案 > 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 类似的答案,但找不到错误的原因。可能是菜鸟的错误。

你能帮我找到它吗?

标签: c#entity-frameworklinqdynamiclinq-to-sql

解决方案


您可以将字符串传递给 where 语句。System.Linq.Dynamic允许您按字符串过滤。

您的代码似乎一切正常,也许您的问题与此有关: https ://github.com/zzzprojects/System.Linq.Dynamic/issues/101

您是否在 dotnetcore 下使用此代码?如果是,请安装相关的 NuGet 包并将使用更改为System.Linq.Dynamic.Core


推荐阅读