开发者

Can I force an expression to be used with a non-nullable parameter?

I'm not sure how to explain this, so I'm gonna show you some code first and explain what it does.

Extension Filter: receives a parameter expression and a special type of filter I've built for my application (IFilter).

public static IQueryable<TSource> Filter<TSource, TProperty>(this IQueryable<TSource> source, Expression<Func<TSource, TProperty>> expression, IFilter f)
{
    if (!f.IsEmpty())
    {
        string propertyName = ExpressionHelper.GetExpressionText(expression);
        source = source.Where(f.GetWhereLambda<TSource>(propertyName));
    }

    return source;
}

Currently, it's possible to do this (simplified!):

var Foo = db.Foos
.Select(e => new
{
    ID = e.ID, // Primary key.
    Bar = e.BarID // Some nullable FK.
})
.Filter(e => e.Bar, this.someSpecialFilter);

So, there's a problem over there. BarID can be null, so the EF is generating a PO开发者_如何学PythonCO class using int?, which is fine for me, but not for my expression processing. This problem first originated this question: How to create a Nullable<T> from a Type variable?.

The problem description:

The exception The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'. is throwed from this code:

return Expression.Equal(leftExpr, rightExpr);

where leftExpr is a System.Nullable1[[System.Int32 (the paramater, as int?) and rightExpr is a System.Int32 (the value, as Int32`).

The question:

Can I do something to avoid the ? from int?? I mean, is it possible to avoid receiving a nullable type or should I check for this in my code?

Thanks a lot,

Ricardo


You want this:

Can I do something to avoid the '?' from 'int?' ?

and then you explain this:

there are situations where th FK is nullable

So i understand you can't avoid the nullable type

this may be a conception issue, or i miss something there


The current solution I've found is use the navigation property and just throw an exception when something is Nullable.

    if ((expression.ReturnType.IsGenericType) && (expression.ReturnType.GetGenericTypeDefinition() == typeof(Nullable<>)))
    {
        throw new Exception("The property expression cannot be Nullable.");
    }

And the use is something like this:

var Foo = db.Foos
.Select(e => new
{
    ID = e.ID, // Primary key.
    Bar = e.Bar.ID // Use the PK from Bar's navigation property.
})
.Filter(e => e.Bar, this.someSpecialFilter);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜