Create Linq Expression for Sql Equivalent "column is null" in c# by creating linq query dynamically

Viewed 377

I have a table with following schema:

  create table test 
  (
    foo1 nvarchar(4),
    foo2 nvarchar(30)
  )
  create unique index test_foo1 on test (foo1);

When created entity using Entity using EF, it generated a class like:

public class Test
{
  public string foo1 {get; set;}
  public string foo2 {get; set;}
}

So when editing this record, I am building dynamic expression tree like below to find if there is a database record for actually editing:

Expression combinedExpression = null;

            foreach (string propertyName in keyColumnNames)
            {
               var propertyInfo = typeof(Entity).GetProperty(propertyName);
               var value = propertyInfo.GetValue(entityWithKeyFieldsPopulated);
               var type = propertyInfo.PropertyType;


                Expression e1 = Expression.Property(pe, propertyName);
                Expression e2 = Expression.Constant(value, type);
                Expression e3 = Expression.Equal(e1, e2);

                if (combinedExpression == null)
                {
                    combinedExpression = e3;
                }
                else
                {
                    combinedExpression = Expression.AndAlso(combinedExpression, e3);
                }
            }

            return combinedExpression;

By doing this whenever I am editing entity "Test" and supplying "null" to property foo1 it is querying database as "select * from test where foo1 == null". How can I build expression that actually creates a where clause as "select *from test where foo1 is null" ?

1 Answers

It might just be that the query processor is not generating an foo1 is null expression because foo1 is in a unique index. It won't be null so it won't generate that expression.

I have some tables with columns declared not nullable and where x.column == null generates where 0 = 1 in its place. It knows it will never be true. Perhaps the same is happening here?

Related