私は、Dapper を DAL レイヤーとして使用するプロジェクトに取り組んでおり、インライン クエリをまだ使用しているためです。クエリを作成するために、dapper sqlBuilder テンプレートを使用しています。
以下は、メソッド コードの 1 つです。
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 がビルダー クラスで必要とする動的パラメーターで動作させる方法が見つからないことです。
すべての提案と助けをいただければ幸いです。