Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jokecamp
Created December 13, 2013 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jokecamp/7951388 to your computer and use it in GitHub Desktop.
Save jokecamp/7951388 to your computer and use it in GitHub Desktop.
ServiceStack v3 Partial Updates
this.RequestFilters.Add((httpReq, httpResp, requestDto) =>
{
var hasFilter = requestDto as IAllowPartialUpdate;
if (hasFilter != null)
{
if (httpReq.QueryString["fields"] != null)
{
// store for later
httpReq.Items.Add("Patch_Fields", httpReq.QueryString["fields"].Split(new[] {','}));
}
}
});
public object Patch(Player request)
{
// works
// Db.UpdateOnly(request, visitor => visitor.Update(p => p.Lastname).Where(x => x.Id == request.Id));
Db.UpdateOnly(request, delegate(SqlExpressionVisitor<Player> visitor)
{
var fields = base.Request.Items["Patch_Fields"] as string[];
if (fields != null)
{
foreach (var field in fields)
{
var match = ModelDefinition<Player>.Definition.FieldDefinitions.FirstOrDefault(x => x.FieldName.ToLower() == field.ToLower());
if (match != null)
visitor.UpdateFields.Add(match.FieldName);
}
}
return visitor.Where(x => x.Id == request.Id);
});
Debug.WriteLine(Db.GetLastSql());
return Db.QueryById<Player>(request.Id);
}
[Test]
public void Can_Do_Partial()
{
var newPlayer = _client.Post(new Player() { Firstname = "fake", Lastname = "fake", DisplayName = "still there"});
var response = _client.Patch<Player>("/players/1?fields=firstname,lastname", new Player() {Id = newPlayer.Id, Firstname = "John", Lastname = "Doe", DisplayName = "Does not update"});
Assert.AreEqual(response.Firstname, "John");
Assert.AreEqual(response.Lastname, "Doe");
Assert.AreEqual(response.DisplayName, "still there");
}
[Test]
public void Can_Do_Partial_Other_object()
{
var newPlayer = _client.Post(new Player() { Firstname = "fake", Lastname = "fake", DisplayName = "still there" });
var response = _client.Patch<Player>("/players/1?fields=firstname,lastname,fake", new { Firstname = "John", Lastname = "Doe", Fake = "fake" });
Assert.AreEqual(response.Firstname, "John");
Assert.AreEqual(response.Lastname, "Doe");
Assert.AreEqual(response.DisplayName, "still there");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment