2

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.

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick response. I am using mongo db where i can store polymorphic field objects. Like checkboxfield i have other classes for different field types. I don't want to add a method in the controller which accepts specific field type. I want to store all information in one go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.