LINQ Dynamic Expression API, predicate with DBNull.Value comparison

Asked
Viewd2541

4

I have an issue using the Dynamic Expression API. I cannot seem to compare a DataTable field against DBNull.Value. The API is supposed to be able to "support static field or static property access. Any public field or property can be accessed.". However given the following query:

 var whatever = table1.AsEnumerable()
                   .Join(table2.AsEnumerable(),
                   (x) => x.Field<int>("Table1_ID"),
                   (y) => y.Field<int>("Table2_ID"),
                   (x, y) => new { x, y})
                   .AsQueryable()
                   .Where("x[\"NullableIntColumnName\"] == DBNull.Value");

I end up getting the error: "No property or field 'DBNull' exists in type '<>f__AnonymousType0`2'"

Anyone have ideas on how to get around this? I can't use Submission.Field("NullableIntColumnName") in the string passed to the Where method either, btw, or else I would be able to compare against null instead of DBNull.Value.

6 个答案

3

好吧,我终于明白了。 cptScarlet几乎拥有它。

 var values = new object[] { DBNull.Value };    
...
.Where("x[\"NullableIntColumnName\"] == @0", values);
 

 .Where("x[\"NullableIntColumnName\"] == @0", DBNull.Value);
 
1

通常,您也可以尝试:

 .Where("NullableColumnName.HasValue");
 
1

当您替换当前版本时会发生什么情况

 .Where(string.format("x[\"NullableIntColumnName\"] == {0}",DBNull.Value));
 
  • Thanks cptScarlet … as soon as I saw your answer I remembered the Where overload that takes a string and params object[] together.

    Richard Anthony HeinJuly 24, 2009 14:54
  • Extremely unlikely to work - {0} gets replaced with null, as that’s waht DBNull.Value.ToString() yields

    Ruben BartelinkJuly 24, 2009 14:47
  • Clarification: Dynamic Linq has its own parser which will be interpreting the string passwed to Where by parsing it as a string expression

    Ruben BartelinkJuly 24, 2009 14:48
1

如果将x.Field<int>("Table1_ID")更改为x.Field<int?>("Table1_ID"),则将获得可为空的整数,而不是常规整数,并且任何DBNull值都将转换为简单的C#空值。仅基于您的代码片段,我什至不确定您是否需要动态表达式-一个简单的.Where(foo => foo.x == null)应该可以工作。

  • I definitely needed dynamic expressions but point taken about using int? for the type parameter.

    Richard Anthony HeinJuly 22, 2010 20:10
0

.Where(a => a.IntColName == null);

编辑:

抱歉,我没有看到这个动态要求...动态应该是:(至少在Framework 4中)

     var intColName = "...";
    .Where(string.Format("it.{0} is null", intColName));
 
  • No I couldn’t have done that, the column choice is dynamic, based on user input.

    Richard Anthony HeinJuly 22, 2010 20:10
0

很抱歉无法使用USL应答,但是...

您是否查看了源代码?没有很多。我的猜测是DBNull不在已注册的根对象列表中。

我现在没有资料来源,但是它也可能告诉您可以与之比较的其他常量。