开发者

How to delegate parts of a where clause to a different area

The particular situation I am currently trying to get around involves a bool? referencing a nullable bit field in the database. But the logic should apply to many different cases.

I am using Entity Framework and have an object with a bool? property. I am starting to write a lot of Linq around this particular property, but because Sql doesnt retrieve null values when bool? != true is written, I am finding I am writing queries that look like:

var Result = from f in FooList
             where f.NullableBool == false || f.NullableBool == null
             where f.Bar.Contains(SearchTerm)
             select f;

This isn'开发者_StackOverflow中文版t a massive problem, but I would really like to be able to remove the "x.NullableBool == false || x.NullableBool == false" to a different place and instead call something like:

var Result = from f in FooList
             where f.IsNot && f.Bar.Contains(SearchTerm)
             select f;

I have tried adding properties and methods of types like 'Expression < Func < Foo, bool > >', 'Func < Foo, bool >' and 'bool' to the Foo class but Linq doesn't seem to like them.

Any pointers greatly appreciated.

Thanks


An extension method of IQueryable should work:

public static class QueryExtensions
{
    public static IQueryable<Foo> WhereIsNot(this IQueryable<Foo> query)
    {
        return query.Where(f => 
            f.NullableBool == false || f.NullableBool == false);
    }
}

Then you can use it this way:

var result = from f in FooList.WhereIsNot()
             where f.Bar.Contains(SearchTerm)
             select f;


I suppose you can write a simple extension method

public static bool IsNot (this Foo f)
{
    return f.NullableBool == false || f.NullableBool == false;
}

and use it like this

var Result = from f in FooList
         where f.IsNot() && f.Bar.Contains(SearchTerm)
         select f;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜