我在c#对象中有以下对象结构
new [] {
new SomeType {
Id = XXX,
SomeSubType = new []{z,y,x,w}
},
.
.
.
}
我正在尝试为Dapper创建类似以下的sql查询。
SELECT *
FROM some_table, some_other_table
WHERE (X = XXX/*@Id*/ AND Y IN (z, y, x, w) /*@SomeSubType*/)
OR (X = AND Y IN (....))
OR (....)
OR (....)
..... )
我可以根据对象动态创建查询,并为每个选项创建很多参数 - 但这很痛苦。
有人能想出更好的方法吗?也许是一个更好的查询,以确保满足这两个条件?
答案 0 :(得分:1)
我认为您正在寻找的是Dapper的SqlBuilder()?
https://github.com/StackExchange/dapper-dot-net/blob/master/Dapper.SqlBuilder/SqlBuilder.cs
How do I build a dynamic sql query with Dapper.SqlBuilder and OrWhere
答案 1 :(得分:0)
如果我理解正确,那么您会列出可能的OR过滤器,如下所示:
var filters = new SomeType[] {
new SomeType { Id = ..., Subtypes = new []{z,y,x,w} },
new SomeType { Id = ..., Subtypes = new []{z,y,x,w} },
new SomeType { Id = ..., Subtypes = new []{z,y,x,w} }, ...
}
您可以使用DapperQueryBuilder 轻松创建动态条件:
var query = cn.QueryBuilder($@"
SELECT *
FROM some_table, some_other_table
/**where**/");
// by default multiple filters are combined with AND
query.FiltersType = Filters.FiltersType.OR;
foreach (var filter in filters)
query.Where($"X = {filter.Id} AND Y IN {filter.Subtypes}");
var results = query.Query<YourPOCO>();
免责声明:我是该库的作者之一