ServiceStack/ServiceStack.OrmLite — pull request #343 by pbedat (2013-11-02 22:59:36+00:00)
Title: fixed broke ToUpdateStatement when PrefixFieldWithTableName is true

*my first ever pull request - feedback appreciated :D*

# The Bug

Setting **PrefixFieldWithTableName** to **true** messes up the update statement:

//ExpressionVisitor
ev.PrefixFieldWithTableName = true;
ev.Update(a => a.Name).ToUpdateStatement(author);
// -> UPDATE "author" SET

# The Test to Prove it

Added the test **Does_generate_valid_update_statement_when_fields_are_prefixed** to **ExpressionTests.cs**

var sut = expr();
sut.PrefixFieldWithTableName = true;

Assert.That(sut.Update(p => p.FirstName).ToUpdateStatement(new Person {FirstName = "Guybrush"}).Trim(),
Is.EqualTo(@"UPDATE ""Person"" SET ""Person"".""FirstName""='Guybrush'"));

# The Fix
When the fields, that are used to generate the statement are picked up, the prefixed fields are ignored because:

if (updateFields.Count > 0 && !updateFields.Contains(fieldDef.Name)) continue; // added

**updateFields** contains the prefixed field names, but the fieldDef.Name is not prefixed.

I refactored the condition into a method called **ContainsUpdateFieldFor**

private bool ContainsUpdateFieldFor(FieldDefinition fieldDef)
{
var expectedNameByFieldDefinition = PrefixFieldWithTableName
? "{0}.{1}".Fmt(
OrmLiteConfig.DialectProvider.GetQuotedTableName(modelDef.ModelName),
fieldDef.Name)
: fieldDef.Name;

return updateFields.Count > 0 && updateFields.Contains(expectedNameByFieldDefinition);
}

Then I corrected the set fields generation with a new method called **GetUpdateAssignmentStatement**:

var column = PrefixFieldWithTableName
? "{0}.{1}".Fmt(
OrmLiteConfig.DialectProvider.GetQuotedTableName(modelDef.ModelName),
OrmLiteConfig.DialectProvider.GetQuotedColumnName(fieldDef.FieldName))
: OrmLiteConfig.DialectProvider.GetQuotedColumnName(fieldDef.FieldName);

var assignedValue = OrmLiteConfig.DialectProvider.GetQuotedValue(value, fieldDef.FieldType);

return return "{0}={1}".Fmt(column, assignedValue);

After skimming the other parts involved in prefixing, I guess there are more similar issues to this one...