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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With