Search code examples
c#asp.netdata-access-layerdtobll

A single DTO class with multiple classes inside


a simple question about DTO, I have a DTO class Cars, and some others subclasses of cars models inside it.

    public class Cars
{
    public Ferrari FerrariModel { get; set; }
    public Porshe PorsheModel {get; set; }
    public Mustang MustangModel { get; set; }
}
    public class Ferrari
{  
    public string collor{ get; set; }
    public int year{ get; set; }
    public double price{ get; set; }
}

and Porshe and Mustang are exactly the same Ferrari. The problem is I do not know how to proceed now. I try something like that

Cars cars = new Cars();
FerrariModel fm = new FerrariModel();
cars.FerrariModel.collor = txtCollor.Text;

And it is not working, as I get the follow error in the cars.FerrariModel.collor -> "Object reference not set paragraph An Instance of hum object . the hum object declaration". I must confess I dont even know it "is possible" or if I am "inventing prograiming", so any help woulb be greatfull.

  1. why use only a single class? Because a need to pass a single DTO in parameters: save(Cars car); update(Cars car)
  2. using a second separeted class would force me to "overload" the method: save(Cars car); save(Ferrari ferrari);
  3. if I use a single class (without Ferrari, Porshe and Mustang) the program work but I have lots of variables in my InteliSense, over 50.

Thank you.


Solution

  • You need to assign your fm instance to your Cars.FerarriModel property.

    Cars cars = new Cars();
    FerrariModel fm = new FerrariModel();
    cars.FerrariModel = fm;
    cars.FerrariModel.collor = txtCollor.Text;
    

    Or even just:

    Cars cars = new Cars();
    cars.FerrariModel = new FerrariModel() { collor = txtCollor.Text };