Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API - Return some fields from model

I'm having this model :

public class Quiz
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int CurrentQuestion { get; set; }
    [JsonIgnore]
    public virtual ICollection<Question> Questions { get; set; } 
}

There is [JsonIgnore] which tells JSON Serializer to ignore this field(Questions). So,I'm having an action which returns serialized Quiz without Questions. I have to implement another action which will return all fields (Questions inclusive). How can I do this ? I need both actions.

like image 834
Maxian Nicu Avatar asked Sep 07 '25 04:09

Maxian Nicu


2 Answers

It's very good practice not to return your domain models from and API. Better way is to create view model classes and return them instead.

So in your example you'd simply create:

public class QuizViewModel 
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int CurrentQuestion { get; set; }
}

and use it to return data from your API.

Obviously in some bigger classes it would be nightmare to crate the code copying all the properties, but don't worry - Automapper (http://automapper.org/) comes to rescue! :)

//Best put this line in app init code
Mapper.CrateMap<Quiz, QuizViewModel>();

//And in your API
var quiz = GetSomeQuiz();
return Mapper.Map<QuizViewModel>(quiz);

You then create another view model class with Questions field in the same way.

like image 149
Michal Dymel Avatar answered Sep 09 '25 02:09

Michal Dymel


You need to slightly change your code as below although its very simple :)

    [Serializable]
    public class Quiz
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int CurrentQuestion { get; set; }
    }

    [Serializable]
    public class QuizWithQuestions : Quiz
    {
        public ICollection<Question> Questions { get; set; }
    }

Now when you want to include Collection of Questions as well use QuizWithQuestions class.

like image 28
Waqar Ahmed Avatar answered Sep 09 '25 01:09

Waqar Ahmed