Lars335 Lars335 - 20 days ago 4x
C# Question

Calculated properties with service reference

I have a WinForms app which uses a Web API (ODATA) server for its data sources. I am binding grids and forms to proxy classes of the service reference.

In some UI fields I need to display calculated values. If I were writing a "standard" WinForms app (without using a service reference and its proxy classes), I would bind to business objects that populate themselves from SQL and let those business objects expose the calculated properties so that I could bind to them from the UI. For example:

public class OrderLine
public string ItemNo { get; set; }
(many other properties here...)
public int Quantity { get; set; }
public decimal Price { get; set; }
public decimal Total { get { return Quantity * Price; } }

I can now do my data binding to Total whereever needed.

But I do not see how to do this when using classes in auto-created service reference proxy classes as the databinding source.

I could of course create local business objects for the databinding and then use these to populate service reference objects when it is time to persist the data or I could do the calculation in the UI (e.g. in the OnChange event [or similar] for the Quantity or Price), but I would rather not if there is a better way. Both lead to code duplication.

What is a good way to deal with calculated properties in this scenario?


Proxy model classes will be generated as partial classes. So you can create a partial model class and add the calculated property. For example:

namespace ProductServiceClient.ServiceReference1
    public partial class Product
        public decimal SomeProperty
                return this.Price * 10;

The namespace is your application default namespace + service reference namespace which you set in Add reference dialog.

Here is a good example for creating a service and service client for those who want to reproduce and solve the problem with minimal effort.