为此,我使用以下功能:
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类似的答案,但是找不到错误的原因。菜鸟错误。
您能帮我找到它吗?
我正在尝试对一个myTables进行动态查询,为此,我使用以下函数:public async Task
search(DBContext db,M model,string uniqueNonIDField){...
System.Linq.Dynamic
允许您按字符串过滤。 您的代码中的所有内容似乎都还不错,也许您的问题与此相关:https://github.com/zzzprojects/System.Linq.Dynamic/issues/101
where
语句作为这样的字符串传递:Where("existingField=123")
,则将其作为表达式Expression<Func<TSource,bool>> predicate
。为了传递该表达式,您将必须知道要过滤的类型