Dapper.net动态OR查询

时间:2015-03-16 22:10:34

标签: dapper

使用Dapper的新手,需要一些帮助。我有一个.csv文件,我将阅读它以动态生成一个select语句。

.csv文件内容如下所示:

id,fromDate,toDate
1,20100101,20110101
2,20110101,20120101
3,20100101,20120101
etc...

我需要动态生成的查询应该是:

SELECT * FROM targetTable WHERE (id = 1 AND cDate BETWEEN 20100101 AND 20110101) OR (id = 2 AND cDate BETWEEN 20110101 AND 20120101) OR 
OR (id = 3 AND cDate BETWEEN 20100101 AND 20120101)

我怎么能用Dapper做到这一点?

1 个答案:

答案 0 :(得分:1)

为什么不简单地构建查询?

假设您在阅读csv后将所有数据都包含在此表单中并将其推送到类中:

public class Data
{
    public int ID { get; set; }
    public int FromDate { get; set; }
    public int ToDate { get; set; }
}

我只是简单地传递查询字符串:

List<string> lines = new List<string>();
foreach (var data in listData) // listData ... List<Data>
{
    string line = string.Format("(id = {0} and cdate between {1} and {2})", data.ID,data.FromDate, data.ToDate);
    lines.Add(line);
}

string additionalQuery = string.Join(" OR ", myLines);

然后......

var result = sqlConnection.Query<MyQueryData>(string.Format("SELECT * FROM targetTable WHERE {0}", additionalQuery));

工作得很好......