Partial classes lost via webservice link

I have a webservice project (old asmx technology) in which I have a User class. This class has a DateTime property that represents this user's date of birth. Apart from this class, I have another file with a partial class User. In this partial class, I add an Age property that returns the user's age:

public partial class User
{
    public DateTime Age
    {
        get { return DateTime.Now - this.Birthdate; }
    }
}

      

The reason this happens in a partial class is because the custom class code is automatically generated from the config file and I cannot add code to that class without deleting it every time the code is generated.

Now, in my webservice, I have a web method that returns a list of these Users it gets from the database:

[WebMethod]
public List<User> GetUsers()
{
    return Database.LoadUsers();
}

      

Simple enough ... Anyway, in another project now I am adding a service reference to this web service. It generates a service client and User class for me. The problem is this: this user class does not contain the properties defined in the partial class (age in this example) ... The webservice does not seem to receive this information.

Of course I can create a new partial User class and basically rewrite it in the second project, but I don't need to, should I? Why doesn't the web service recognize the partial class?

+3


source to share


2 answers


Partial classes are not extension methods. They are brought together in 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 reference to a new project. This will be the same file, but linked in a new project. When you go to Add - Existing Item, select the Open arrow and select Add as Link.

Option 2

Create an extension method:

public static class DateExtensions
{
    public TimeSpan GetAge(this DateTime birthDate)
    {
        return DateTime.Now - birthDate;
    }
}

      



Then just add a statement using

for whatever namespace your extension class is in and make sure the project / assembly reference is specified and you can call this:

// This is your BirthDate property that would come back and is DateTime
var birthDate = new SomeService().DoSomething().BirthDate;

var age = birthDate.GetAge();

      

Option 3

Create a separate project and put the service link and the partial in it. Project reference (and required base references) from your projects.

I created an example to view / use on GitHub .

+3


source


If you have to tie your customer tightly to your service, you can get the service link to reuse the same types used by the service. Just move the types in question to their own project and assembly, and link to both client and server projects.



I doubt this works with a WCF service, but I have never done it with an ASMX service.

0


source







All Articles