Yasser Shaikh
Yasser Shaikh

Reputation: 47774

Best way to return update status from repository layer in ASP.NET MVC WEB API

I am using ASP.NET Web API with Entity Framework and Backbone.js

I am working on an update module, where user is allowed to update his XYZ.

Now, there are 3 cases which may occur while updating

So I have decided to use this enum called

enum UpdateStatus
{
    Success = 1,
    Failed = 0,
    NotFound = 2
}

so here is what my methods will look like

public UpdateStatus UpdateXYZ(Model model)
{
    var data = _repo.Table.where(m => m.id == model.id);
    if(data.count == 0)
    {
        return UpdateStatus.NotFound;
    }

    try
    {
        // update here
        return UpdateStatus.Sucess; 
    }
    catch
    {
        // log errors
        return UpdateStatus.Failed;
    }
}

Then later in the service layer I would be returning the same values to my web api action. And then in the web api action I would have something like...

public HttpResponseMessage Put(Details details)
{
    if (ModelState.IsValid)
    {
        //The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent.
        //return new HttpResponseMessage(HttpStatusCode.ResetContent);
        UpdateStatus = _magicService.UpdateXYZ(details);
        if (UpdateStatus.Success)
        {
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
        else if(UpdateStatus.NotFound)
        {
            return new HttpResponseMessage(HttpStatusCode.Gone);
        }
        return new HttpResponseMessage(HttpStatusCode.Conflict);
    }
    else
    {
        string messages = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage + " - " + (x.Exception == null ? "" : x.Exception.Message)));
        return Request.CreateResponse<string>(HttpStatusCode.BadRequest, messages.ToString());
    } 

}   

I have defined my UpdateStatus enum in my repo layer and am using it in Service and Web layers also. Would like opinions on this approach or is there any other way I could have done this ?

Please share your thoughts on this.

Upvotes: 0

Views: 821

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038750

It's fine as long as your domain models are not leaving the boundaries of your Web API for which you should be using view models.

Upvotes: 1

Related Questions