user2614389
user2614389

Reputation: 57

c# web api derived type is not serialised

I have a requirement to store various types of fields in Db. I have base field class with all common property and I have derived classes with specific properties for each field type.

public class BaseField
{
   public string ID{get;set;}
   public string Name{get;set;}
}

public class CheckboxField:BaseField
{
   public bool Checked{get;set;}
}

I have an asp.net core web API method that accepts BaseField as a parameter. When I try to save an object of type CheckboxField it is always converted BaseField. I know that as the parameter is of type BaseField, it is always serializing to BaseField but I want to know how can I handle saving checkbox field using the same method.

Upvotes: 2

Views: 159

Answers (1)

Arsen Khachaturyan
Arsen Khachaturyan

Reputation: 8330

I have an asp.net core web API method that accepts BaseField as a parameter. When I try to save an object of type CheckboxField it is always converted BaseField.

Yes and that is actually how it should work because your method accepts Base class and you call it with the derived type, which will make to cast back to Base class.

I know that as the parameter is of type BaseField, it is always serializing to BaseField but I want to know how can I handle saving checkbox field using the same method.

Well, let's first understand one major thing here, do you actually DB table have the Checked column, or you have one table for Base class and another for Checkbox.

If the answer is yes, your DB table has the Checked column along with other columns from the BaseField then basically replace your method to accept the CheckboxField instead of BaseField as a parameter.

Note: if you will still want a default value for Checked value in case if the method is called with BaseField parameter, you can create a method override for this particular case:

public void DoSomeChange(CheckboxField data) {
 ...
}

public void DoSomeChange(BaseField data) {
   var cData = new CheckboxField { 
    // initialize properties here, or create override constructor accepting BaseField in  
    // CheckboxField 
   };

   cData.Checked = true; // or false, it depends on what you need

   DoSomeChange(cData);
}

Upvotes: 1

Related Questions