1

任何人都可以建议一个库通过 lambda 表达式构建原始 sql 代码吗?不要建议 EF 和 Linq2sql,因为它不提供对查询的控制。

像这样的东西。这是我自己库中的代码。但是,如果这种情况有另一个好的解决方案,我不希望支持这一点。

[Fact]
public void TotalTest()
{
    var countFld = SqlField<Person>.Count(p => p.LastName);
    var select = new SqlSelect<Person>()
        .AddFields(p => p.LastName, p => p.Name)
        .AddFields<Passport>(p => p.Number)
        .AddField(countFld)
        .InnerJoin<Person, Passport>((person, passport) => person.Id == passport.PersonId)
        .Where(SqlFilter<Passport>.From(p => p.Number).IsNotNull().And(p => p.Number).NotEqualTo("3812-808316"))
        .GroupBy(p => p.LastName)
        .Having(SqlFilter<Person>.From<int>(countFld).GreaterThan(2))
        .OrderBy(p => p.LastName);

    var expected =
@"SELECT
    pe.LastName, pe.Name, pa.Number, COUNT(pe.LastName)
FROM
    Person pe
INNER JOIN
    Passport pa ON pe.Id = pa.PersonId
WHERE
    pa.Number IS NOT NULL AND pa.Number <> '3812-808316'
GROUP BY
    pe.LastName
HAVING
    COUNT(pe.LastName) > 2
ORDER BY
    pe.LastName";
    Assert.Equal(expected, select.CommandText);
}
4

1 回答 1

1

我已经使用 nuget 包将 lib 发布到了 GitHub。它包含基本场景,并将根据需要进行更新。已经支持设置字段、where、group by、have、order by、joins、嵌套查询。

https://github.com/Serg046/LambdaSql

例子:

var qry = new SqlSelect
(
    new SqlSelect<Person>()
        .AddFields(p => p.Id, p => p.Name)
        .Where(SqlFilter<Person>.From(p => p.Name).EqualTo("Sergey"))
    , new SqlAlias("inner")
).AddFields<Person>(p => p.Name);

Console.WriteLine(qry.ParametricSql);
Console.WriteLine("---");
Console.WriteLine(string.Join("; ", qry.Parameters
    .Select(p => $"Name = {p.ParameterName}, Value = {p.Value}")));

输出:

SELECT
    inner.Name
FROM
(
    SELECT
        pe.Id, pe.Name
    FROM
        Person pe
    WHERE
        pe.Name = @w0
) AS inner
---
Name = @w0, Value = Sergey
于 2017-12-25T16:23:06.653 回答