我的课程如下:
public class SqlQueryObjContainer
{
public FilterClause Clause { get; set; }
}
public class FilterClause
{
public List<WhereClause> WhereClauses { get; set; }
public List<HavingClause> HavingClauses { get; set; }
}
public class WhereClause
{
public string Field { get; set; }
public string Operator { get; set; }
}
public class HavingFilter
{
public string Field { get; set; }
public string Operator { get; set; }
}
这是我的sql查询,其中包含where和having子句,如下所示:
select id,name from table where dbo.table.Column1 > 0 or dbo.table.Column2 > 0
group by id,name having COUNT(id) < 4 AND COUNT(id) > 2
SO where子句包含具有2个条件的记录:
[0] : Field = dbo.table.Column1 > 0
Operator = null
[1] : Field = dbo.table.Column2 > 0
Operator = or
Having子句将具有如下记录:
[0] : Field = COUNT(id) < 4
Operator = null
[1] : Field = COUNT(id) > 2
Operator = and
以下是我创建where和having子句的代码:
string query = "select * from table"
var i = 0;
if (sqlObj.Clause != null)
{
query = query + " where ";
if (sqlObj.Clause.Whereclauses != null)
{
foreach (var where in sqlObj.Clause.Whereclauses)
{
if(i > 0)
{
query = query + " " + where.Operator + " ";
}
query = query + where.Field;
i++;
}
}
}
// above same repeated code for generating having clause
上面同样的代码也重复了for having子句因为你可以看到where和过滤器都有相同格式的记录,所以有可能创建1个泛型方法,它将在1方法中具有这个通用逻辑并基于我将传递(where或having子句),如果where子句:
,它将返回如下所示的字符串dbo.table.Column1 > 0 or dbo.table.Column2 > 0
我在想下面的内容,但没有得到:
private string CreateFilterClause<T>()
{
}
答案 0 :(得分:2)
我不想深入了解你想要实现的目标,但你可以在你的子句中添加基类或接口。
interface IClause
{
string Field { get; set; }
string Operator { get; set; }
}
public class WhereClause : IClause
{
public string Field { get; set; }
public string Operator { get; set; }
}
public class HavingFilter : IClause
{
public string Field { get; set; }
public string Operator { get; set; }
}
您可以创建一个方法:
static string CreateFilterClause<IClause>(IClause param)
{
string text = string.Empty;
// you can now access the Field and Operator properties for param.
return text;
}
并使用它:
string text = CreateFilterClause<WhereClause>(new WhereClause());