Reputation: 125
I hope this question has been asked before and I am just not finding it. I am writing a set of Restful API's in WebAPI2. I understand that the API Controllers will be returning models in their response. My question is, can I create dynamic properties in these models, when additional data is needed?
For example, I may have a class that looks like this:
public class FooModel
{
public int FooId{get;set;}
public string Description{get;set;}
}
public class BarModel
{
public int BarId{get;set;}
public string Description{get;set;}
}
I can create a service that will retrieve just a Foo, save a Foo, etc. But what if I need a service that will return a Foo, and all of the Bar's associated with that Foo. So the return class will need to look like this:
public class FooModel
{
public int FooId{get;set;}
public string Description{get;set;}
public List<BarModel> Bars{get;set;}
}
Do I need to create a whole new model for this? Or is there a way in WebAPI that I can dynamically add the Bars property to the FooModel.
In this use case, when saving a Foo, I wouldn't know the Bars associated with it. In addition, to reduce bandwidth there are places in my frontend code where I need to get a Foo without all of the Bars (otherwise it would send a lot of data, which wouldn't be used).
Does that make sense?
Any ideas would be greatly appreciated.
Ben
Upvotes: 1
Views: 342
Reputation:
Use DTO's and use default values.
public class FooModel
{
[DefaultValue(0)]
public int FooId { get; set; } = 0;
[DefaultValue("")]
public string Description { get; set; } = "";
public List<BarModel> Bars { get; set; }
public bool ShouldSerializeBars() { return Bars != null && Bars.Any(); }
}
If FooId = 0 then the field will be omitted. This counts for attributes as well for elements. You'll need to add an attribute, but also actually set the default value.
You can also inherit from other classes to extend DTO's.
public class FooModel2 : FooModel
{
[DefaultValue(0)]
public int FooId2 { get; set; } = 0;
}
This one has all the fields of FooModel and the field FooId2.
Upvotes: 1