任何人都可以建议lib通过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);
}
答案 0 :(得分:0)
我已经使用nuget包将lib发布到GitHub。 它包含基本方案,并将根据需要进行更新。已经支持设置字段,where,group by,having,order by,join,嵌套查询。
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