Quantcast
Channel: ささいなことですが。
Viewing all articles
Browse latest Browse all 104

LambdaでSQLを書きたい - ①LambdicSql始めました

$
0
0

文字列でSQL書くのが苦手なのです。

SQL弱者としてはインテリセンスなしでSQL書くの辛いんです。(Friendyでdynamic使わせてるのにって怒られそうですが)コード中に文字列演算がバンバン入るのがイマイチですしね。何とかしたいよなー。

LambdicSql始めました。

EntityFrameworkみたいにラムダでSQL書ければいいじゃん。ってことで、そんなライブラリ作り始めました。Lamdicなんて単語はないですけどねw。まあ雰囲気伝わるでしょう。.Net3.5から使えます。(EF使えないプロジェクトとかレガシー資産にこそ多い)
www.nuget.org
github.com

ラムダでSQLが書けます。

publicclass Staff
{
    publicint id { get; set; }
    publicstring name { get; set; }
}

publicclass Remuneration
{
    publicint id { get; set; }
    publicint staff_id { get; set; }
    public DateTime payment_date { get; set; }
    publicdecimal money { get; set; }
}

publicclass DB
{
    public Staff tbl_staff { get; set; }
    public Remuneration tbl_remuneration { get; set; }
}

publicclass SelectedData
{
    publicstring Name { get; set; }
    public DateTime PaymentDate { get; set; }
    publicdecimal Money { get; set; }
}
//これ重要using Dapper;
using LambdicSql;
using LambdicSql.feat.Dapper;
usingstatic LambdicSql.Keywords;
usingstatic LambdicSql.Funcs;
usingstatic LambdicSql.Utils;

publicvoid TestStandard()
{
    var min = 3000;

    //これが(割と)そのままSQLになる
    var query = Sql<DB>.Create(db =>
        Select(new SelectedData()
        {
            Name = db.tbl_staff.name,
            PaymentDate = db.tbl_remuneration.payment_date,
            Money = db.tbl_remuneration.money,
        }).
        From(db.tbl_remuneration).
            Join(db.tbl_staff, db.tbl_staff.id == db.tbl_remuneration.staff_id).
        Where(min < db.tbl_remuneration.money && db.tbl_remuneration.money < 4000));

    //文字列生成
    var info = query.ToSqlInfo(_connection.GetType());
    Debug.Print(info.SqlText);

    //Dapperを使っているなら、以下のように実行できます
    var datas = _connection.Query(query).ToList();
}

こんなSQLが出力されます。

SELECT
    tbl_staff.name AS Name,
    tbl_remuneration.payment_date AS PaymentDate,
    tbl_remuneration.money AS Money
FROM tbl_remuneration
    JOIN tbl_staff ON (tbl_staff.id) = (tbl_remuneration.staff_id)
WHERE ((@min) < (tbl_remuneration.money)) AND ((tbl_remuneration.money) < (@p_1))

このブログで機能紹介していこうと思っています。

仕様変更がありました。

2016/07/04 ソースコード修正
2016/07/09 SQL修正 プリペアド対応
2016/09/02 β版


Viewing all articles
Browse latest Browse all 104

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>