使用Reflection构建Dapper SQL Builder查询参数

时间:2015-06-11 05:25:34

标签: c# sql reflection dapper

我正在处理使用Dapper作为DAL图层的项目,因为我们仍在使用内联查询。为了构造我们的查询,我们使用dapper sqlBuilder模板。

以下是我们的方法代码之一:

SqlBuilder builder = new SqlBuilder();
        var update = builder.AddTemplate("DECLARE @transactionID bigint; " +
                                         "EXEC @transactionID = dbo.sp_getAndIncrementTransactionCounter @accountID; " +
                                         "UPDATE TimeEntryIndex /**set**/ OUTPUT inserted.id /**where**/");

        builder.Set("userID         = @userID", new { field.UserId });
        builder.Set("deviceID       = @deviceID", new { field.DeviceId });
        builder.Set("deviceName     = @deviceName", new { field.DeviceName });
        builder.Set("transactionID  = @transactionID");
        builder.Set("state          = @state", new { ttContent.state });
        builder.Set("lastUpdated    = GETUTCDATE()");

        // Determine which fields to update
        if (!string.IsNullOrEmpty(ttContent.title))
        {
            builder.Set("title = @title", new { ttContent.title });
        }
        if (!string.IsNullOrEmpty(ttContent.description))
        {
            builder.Set("description = @description", new { ttContent.description });
        }
        if (tEntryIndex.finish.HasValue)
        {
            builder.Set("finish = @finish", new { tEntryIndex.finish });
        }
        if (ttContent.created.HasValue)
        {
            builder.Set("created = @created", new { ttContent.created });
        }
        if (tEntryIndex.duration.HasValue)
        {
            builder.Set("duration = @duration", new { tEntryIndex.duration });
        }

        builder.Where("accountid = @accountid", new { accountid = field.AccountId });
        builder.Where("id = @id", new { id = timeEntryId });

        var result = new Result<long?>(sqlConn.ExecuteScalar<long?>(update.RawSql, update.Parameters));

在上面的代码中,它适用于数据库中的少量字段。但是当我们在表格中有很多字段时,让我们说25列,只需要构建那个构建器就可以做很多工作。

我想用反射将它包装在一个函数中。我首先尝试这样的事情:

foreach (PropertyInfo prop in typeof(Account).GetProperties())
{
   // Will do checking on every type possible
   if (typeof(String).IsAssignableFrom(prop.PropertyType) && prop.GetValue(aContent) != null && !string.IsNullOrEmpty(prop.GetValue(aContent).ToString()))
   {
       builder.Set(string.Format("{0} = @{0}", prop.Name.ToLowerInvariant()), new { <what should I put in here> });
   }
 }

问题是我无法找到一种方法使其适用于Dapper在其构建器类上需要的动态参数。

非常感谢每一个建议和帮助。

0 个答案:

没有答案