Wanted some opinions on something I have been working with, I've tried a few ways of structuring the way I retrieve and return data to my WebAPI, and I'm pretty happy with what I have so far, but I was looking for a comparison of the pro's and con's of using models vs entities for returning data on the WebAPI.
In my opinion, from what I've seen, adding a model factory and returning models is good because you get control over what your object looks like, but it does mean you now have to map the entities to that model somewhere, increasing the code you have to write, particularly if you have a lot of entities.
On the other hand, having partial classes of the generated objects allows me the same extensibility, and by adding a meta data class using MetadataType(typeof(typename))
, I am able to decide what will be serialized and how they are built, giving me full control again over the structure, and being able to extend it when I want to, rather than having to for every entity.
So, if I can get the same benefits with partials and metadata, without the additional code in mapping to models, what are other downsides, how come this approach is not as common? I mean, if I wanted I could do the mapping this way too, without the need for any factories to do the mapping, just by attributing the fields to be ignored and creating new ones with Get/Set to point to the original property.
An example:
Generated by T4 template:
public partial class FileHeader : BaseEntity
{
public FileHeader()
{
this.FileVersionSubs = new HashSet<FileVersion>();
}
public int FileId { get; set; }
public string Name { get; set; }
public string Caption { get; set; }
public virtual ICollection<FileVersion> FileVersionSubs { get; set; }
}
The partial I make:
[MetadataType(typeof(FileHeaderMetaData))]
public partial class FileHeader
{
// Additional fields go here
}
Metadata file:
public class FileHeaderMetaData
{
// Any attributes for existing fields here, eg:
[MyCustomAttribute]
public int FileId { get; set; }
}
If I were to approach this from a Model point of view, I would be repeating the same properties for every class I generate and wanted to return as well as mapping them, rather than the ones I explicitly want to change or hide.
Thoughts, feelings and suggestions welcome!