Home > Software engineering >  C# Nesting an object in a model without using a View Model
C# Nesting an object in a model without using a View Model

Time:05-25

Currently I have two objects both populated with stored procedure, then combine them in a view model.

VMGeneric{
   public GeneralStats Stats {get; set;}
   public GeneralInfo Info {get; set;}

   VMGeneric(GeneralStats stats, GeneralInfo info)
   {
      this.Stats = stats;
      this.Info = info; 
   } 
}

GeneralStats{
   public int Stats1 {get; set;}
   public int Stats2 {get; set;}
}

GeneralInfo{
   public int Stats1 {get; set;}
   public int Stats2 {get; set;}
}

However this violates our contract with the frontend team. Which is defined as:

GeneralStats{
   public int Stats1 {get; set;}
   public int Stats2 {get; set;}
   public GeneralInfo Info {get; set;}
}

Is there a way to populate the the GeneralStats object with a stored procedure and the GeneralInfo object (that is also populated by a stored procedure) in the same call?

CodePudding user response:

Try to use an anonymous object as below

var GeneralStats = new { Test1 = new Test1(), Test2 = new Test2(), Demo = new { } };

CodePudding user response:

I suggest changing your view model to match the frontend model:

public class VMGeneric
{
    public int Stats1 { get; set; }
    public int Stats2 { get; set; }
    public GeneralInfo Info { get; set; }

    public VMGeneric(GeneralStats stats, GeneralInfo info)
    {
        this.Stats1 = stats.Stats1;
        this.Stats2 = stats.Stats1;
        this.Info = info;
    }
}
  • Related