开发者

Table-value functions in BLToolkit

Is it possible to use SQL Server table-value functions by using the BLToolkit library?

I would like开发者_Python百科 to use it within the Linq query, but I couldn't find anything regarding this on the library wiki.


Define your function in your data context class as the following:

[TableFunction(Name="GetParentByID")]
public Table<Parent> GetParentByID(int? id)
{
    return GetTable<Parent>(this, (MethodInfo)MethodBase.GetCurrentMethod(), id);
}

Usage:

[Test]
public void Func2()
{
    using (var db = new TestDbManager())
    {
        var q =
            from c in db.Child
            from p in db.GetParentByID(2)
            select p;

        q.ToList();
    }
}

SQL:

SELECT
    [t2].[ParentID],
    [t2].[Value1]
FROM
    [Child] [t1], [GetParentByID](2) [t2]

Also you can define it outside of the data context:

public class Functions
{
    private readonly IDataContext _ctx;

    public Functions(IDataContext ctx)
    {
        _ctx = ctx;
    }

    [TableFunction]
    public Table<Parent> GetParentByID(int? id)
    {
        return _ctx.GetTable<Parent>(this, (MethodInfo)(MethodBase.GetCurrentMethod()), id);
    }

    [TableExpression("{0} {1} WITH (TABLOCK)")]
    public Table<T> WithTabLock<T>()
        where T : class 
    {
        return _ctx.GetTable<T>(this, ((MethodInfo)(MethodBase.GetCurrentMethod())).MakeGenericMethod(typeof(T)));
    }
}

[Test]
public void Func1()
{
    using (var db = new TestDbManager())
    {
        var q =
            from p in new Functions(db).GetParentByID(1)
            select p;

        q.ToList();
    }
}

[Test]
public void WithTabLock()
{
    using (var db = new TestDbManager())
    {
        var q =
            from p in new Functions(db).WithTabLock<Parent>()
            select p;

        q.ToList();
    }
}

SQL:

SELECT
    [p].[ParentID],
    [p].[Value1]
FROM
    [GetParentByID](1) [p]

SELECT
    [p].[ParentID],
    [p].[Value1]
FROM
    [Parent] [p] WITH (TABLOCK)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜