Atle Kristiansen
Atle Kristiansen

Reputation: 707

PATCH in ServiceStack

I am trying to patch a object with the following code.

public object Patch(EditBlog request)
{
     using (var db = _db.Open())
     {
         try
         {
            request.DateUpdated = DateTime.Now;
            Db.Update<Blog>(request, x => x.Id == request.Id);
            return new BlogResponse { Blog = Blog = Db.Select<Blog>(X=>X.Id == request.Id).SingleOrDefault()};
         }
         catch (Exception e)
         {

             return HttpError.Conflict("Something went wrong");
         }
     }
 }

In Postman, I am calling the function like this "api/blog/1?=Title=Test1&Summary=Test&UserId=1". When debugging I can see that those values has been assigned to the request. During the Update it throws: "Cannot update identity column 'Id'"

My model looks like this

public class Blog
{
    [AutoIncrement]
    public int Id { get; set; }

    public IUserAuth User { get; set; }
    [Required]
    public int UserId { get; set; }

    [Required]
    public string Title { get; set; }
    public string Summary { get; set; }
    public string CompleteText { get; set; }

    [Required]
    public DateTime DateAdded { get; set; }

    public DateTime DateUpdated { get; set; }

}

And the EditBlog DTO looks like this:

[Route("/api/blog/{id}", "PATCH")]
public class EditBlog : IReturn<BlogResponse>
{
    public int Id { get; set; }
    public IUserAuth User { get; set; }
    public int UserId { get; set; }
    public string Title { get; set; }
    public string Summary { get; set; }
    public string CompleteText { get; set; }
    public DateTime DateUpdated { get; set; }
}

Upvotes: 1

Views: 141

Answers (1)

mythz
mythz

Reputation: 143284

The error message "Cannot update identity column 'Id'" does not exist anywhere in ServiceStack.OrmLite, it could be an error returned by the RDBMS when you're trying to update the Primary Key which OrmLite wouldn't do when updating a Model annotated with a Primary Key like your Blog class has with its annotated [AutoIncrement] Id Primary Key.

The error is within your Db.Up<T> method that's performing the update, which is not an OrmLite API, so it's likely your own custom extension method or an alternative library.

I would implement a PATCH Request in OrmLite with something like:

var blog = request.ConvertTo<Blog>();
blog.DateUpdated = DateTime.Now;
Db.UpdateNonDefaults(blog);

i.e. using OrmLite's UpdateNonDefaults API to only update non default fields and updating using the Blog Table POCO not the EditBlog Request DTO.

Also you should use the Single APIs when fetching a single record, e.g:

Blog = Db.SingleById<Blog>(request.Id)

or

Blog = Db.Single<Blog>(x => x.Id == request.Id)

Instead of:

Blog = Db.Select<Blog>(X=>X.Id == request.Id).SingleOrDefault()

Upvotes: 1

Related Questions