Web API 2 - Restrict Data Model using an Interface

224 views Asked by At

I have a model that is created from a Linq To SQL class. The model looks like this:

public class Person
{
    public int id;
    public string userName;
    public string firstName;
}

I want to use Data Annotations so I implemeneted an interface called IPerson

interface IPerson
{
    [Required]
    public int id;
    [Required]
    public string userName;
    [Required]
    public string firstName; 
}

Then changed my model to this:

[MetadataType(typeof(IPerson))]
public class Person: IPerson
{
    public int id;
    public string userName;
    public string firstName;
}

This works well, however, I have the following issues:

  • I'd like to exclude some data members (i.e firstName) from getting serialized back in the controller action. To do this, I'd like to use DataContract, however, I cannot use this in the interface IPerson as it only works with classes or Enums. I do not want to implement the Data Contract directly in the Person model because I'm likely to add new columns to my SQL databases (which will generate new model classes) and I'd like to keep data access layer loosely coupled with my business logic.

How can I exclude data members from being serialized in the JSON responses I'm sending to the clients this in the most neat way?

1

There are 1 answers

0
RonaDona On BEST ANSWER

I fixed it, I used:

using Newtonsoft.Json;

then used [JsonIgnore] on the data members I did not want to serialize in the interface IPerson.