I have a web service in asp.net and I have this model to return:
[Seriazable]
public class Package {
public int Id { get; set; }
public string Name { get; set; }
public string List<Document> Documents { get; set; }
public Package() { }
}
And in my web service I have these methods:
[WebMethod]
public Package GetPackage(int Id);
[WebMethod]
public List<Package> FindPackage();
The first method is ok (all properties are returned and it works fine), but the on second method I don’t want to expose Documents property, only the Id and Name… how can I do it?
Thanks
Since you don’t want the consuming client to have access to the documents, you should create a separate view model1 class for the second method to serve. Something like this:
You can then instantiate objects of this class using some mapping utility, for example AutoMapper, and return those instead:
Karel Frajtak suggested you use a similar view model object also for the package, but since they are identical that will only clutter your code – as long as the
Packageis a simple POCO, there is no need for an extra class. However, if you are using some O/R-mapper that keeps track ofPackageinstances, it is wise not to expose them to the client app. Then you should instead do what Karel suggested, and create a POCO view model class for thePackageas well.1) Some call them Data Transfer Objects (DTO). I call them View Models. I bet there are ten other names out there too – for all practical purposes, they are the same.