I have a webservice project (old asmx technology) in which I have a class User. This class has a DateTime property that represents the birthdate of this user. Beside this class, I have another file with a partial class User. In this partial class, I add a property ‘Age’ which returns the age of the user:
public partial class User
{
public DateTime Age
{
get { return DateTime.Now - this.Birthdate; }
}
}
The reason that this is in a partial class is because the User class code is automatically generated from a config file, and I cannot add code to this class without it being removed every time the code is generated.
Now in my webservice I have a webmethod that returns a list of these Users which it gets from a database:
[WebMethod]
public List<User> GetUsers()
{
return Database.LoadUsers();
}
Simple enough… Anyway, in a different project now, I add a Service Reference to this webservice. It generates the service client and a User class for me. The problem is: this User class does not contain the properties defined in the partial class (Age in this example)… It seems the webservice doesn’t get this information.
Of course I can create a new partial User class and basically rewrite it in the second project, but I shouldn’t have to, should I? Why doesn’t the webservice recognize the partial class?
Partial classes are not extension methods. They are compiled together into one class in each assembly. You have two options for what you want to do:
Option 1
Add the partial class you wrote as a link to the new project. It will be the same file, but linked into the new project. When you go to Add -> Existing Item, select the arrow by Open and choose “Add as Link”.
Option 2
Create an extension method:
Then, just add a
usingstatement for whatever namespace your extension class is in, and make sure the project/assembly is referenced, and you can call this:Option 3
Create a separate project and put the service reference and partial in it. Reference the project (and the necessary framework references) from your using projects.
I have created an example for you to view/use on GitHub.