开发者

Linq to SQL writing translatable functions

I'm pretty sure the answer to this is "you can't do that" or "No, no, you misunderstand...", but:

I have a linq class, thing, which will happily execute this:

 var thingsWithAandB = from t in db.things
                       where t.propA.HasValue && t.propB.HasValue
                       select t;

But I do this a lot, and so I want:

partial class thing
{
    public bool hasAandB
    {
        get
        {
            return propA.HasValue && propB.HasValue;
        }
    }
}

and then:

var thingsWithAandB = from t in db.things where t.hasAandB select t;

But of course, when I do this, I get "Can't translate that into SQL" errors. And I understand that this is because calling methods in the middle of SQL queries isn't possible, since my code and the database are separate.

开发者_Python百科What's the way to do this? Is it impossible?


It is perfectly possible. Damien Guard (damieng.com) has a sample on his blog showing how to do that.

http://damieng.com/blog/2009/06/24/client-side-properties-and-any-remote-linq-provider


You can use extension methods:

public static class MyExtensions{
    public static bool HasAandB(this thing t){
        return t.propA.HasValue && t.propB.HasValue;
    }
}

and then use it:

var thingsWithAandB = from t in db.things
                   where t.HasAandB()
                   select t;

EDIT
Sorry, this will probably give you the same exception...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜