Skip to content

Instantly share code, notes, and snippets.

@jrosskopf
Created February 20, 2012 16:42
Show Gist options
  • Save jrosskopf/1870052 to your computer and use it in GitHub Desktop.
Save jrosskopf/1870052 to your computer and use it in GitHub Desktop.
CustomSqlServerOrmLiteDialectProvider.cs
namespace ServiceStack.OrmLite.CustomSqlServer
{
public class CustomSqlServerOrmLiteDialectProvider : SqlServerOrmLiteDialectProvider
{
public new static CustomSqlServerOrmLiteDialectProvider Instance = new CustomSqlServerOrmLiteDialectProvider();
private const string VARIABLE_CHARACTER = "@";
public void PrepareForInsertRowStatement(object objWithProperties, System.Data.IDbCommand command)
{
PrepareForInsertRowStatement(objWithProperties, null, command);
}
public void PrepareForInsertRowStatement(object objWithProperties, IList<string> insertFields, System.Data.IDbCommand command)
{
if (insertFields == null) insertFields = new List<string>();
var sbColumnNames = new StringBuilder();
var sbColumnValues = new StringBuilder();
var modelDef = objWithProperties.GetType().GetModelDefinition();
command.Parameters.Clear();
int i = 0;
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.AutoIncrement) continue;
//insertFields contains Property "Name" of fields to insert ( that's how expressions work )
if (insertFields.Count > 0 && !insertFields.Contains(fieldDef.Name)) continue;
if (sbColumnNames.Length > 0) sbColumnNames.Append(",");
if (sbColumnValues.Length > 0) sbColumnValues.Append(",");
try
{
sbColumnNames.Append(GetNameDelimited(fieldDef.FieldName));
if (DbTypes.ColumnDbTypeMap.ContainsKey(fieldDef.FieldType))
{
sbColumnValues.AppendFormat("{0}{1}", VARIABLE_CHARACTER, fieldDef.FieldName);
AddParameterToCommand(command, fieldDef, objWithProperties);
}
else
{
sbColumnValues.Append(fieldDef.GetQuotedValue(objWithProperties));
}
}
catch (Exception ex)
{
throw;
}
}
command.CommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2});",
GetTableNameDelimited(modelDef), sbColumnNames, sbColumnValues);
}
private void AddParameterToCommand(IDbCommand command, FieldDefinition fieldDef, object objWithProperties)
{
var p = command.CreateParameter();
p.ParameterName = String.Format("{0}{1}", VARIABLE_CHARACTER, fieldDef.FieldName);
p.DbType = DbTypes.ColumnDbTypeMap[fieldDef.FieldType];
p.Value = GetValueOrDbNull(fieldDef, objWithProperties);
command.Parameters.Add(p);
}
private object GetValueOrDbNull(FieldDefinition fieldDef, object objWithProperties)
{
return fieldDef.GetValue(objWithProperties) ?? DBNull.Value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment