How do I add properties to a Web API Response that I do not store in my DB?

asp.net-web-api asp.net-web-api2 c# entity-framework entity-framework-6

Question

I'm used Entity Framework 6.0 to create a C# Web API. The simplest User Class I have has 3 characteristics, and I use SQL to persist it into a User Table with 3 related columns, with UserID serving as the Primary Key.

public partial class User
{
    public string UserID {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

I don't want to store these two output-only characteristics in my database, thus I want to add them to the Web API on the spot. I utilize these attributes to send "Status" and "Message" information to the consuming client that isn't a part of the User Class. Status: OK, Error, or Warning. Any communication that the Web API needs to relay to the calling client would be considered a message.

What is the easiest technique, WITHOUT changing the underlying User Table on SQL, to add these two properties instantly when returning the Web API response? I am aware that I can include these two in the User Table as dummy columns. When I don't need it, I don't want to carry about that burden on the SQL side.

1
1
3/27/2016 10:13:31 PM

Accepted Answer

ZZZ_tmp
1
3/28/2016 9:14:57 AM

Popular Answer

A data transfer object (DTO) class with all the features you need should ideally be created in model, and then you should utilize a mapper to map your user to the DTO.

public class UserDto{
   public string UserID {get; set;}
   public string FirstName {get; set;}
   public string LastName {get; set;}

   public string Message {get; set;}
   public string Status {get; set;}
}

therefore, in your deed

[ResponseType(typeof(UserDto))]
public IHttpActionResult User(string userId){

   // retrive user from db

   var userDto = Mapper.Map<UserDto>(dbUser);

   if(condition){
      userDto.Message = "the message";
      userDto.Status = "the status";
   }

   return Ok(userDto);
}

Then you may configure Automapper to perform the mapping for you after installing it from nuget.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow