Pergunta

I am using WCF Data Services to provide OData endpoints as part of my service. Recently I had a requirement to add a property to one of the entites but I do not want this returned as part of the Service.

I am using code first, My entity is similiar to:

[DataServiceEntity]
public class Customer 
{
    [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int customer_id { get; set; }

    [Required]
    public string customer_name { get; set; }

    public int customer_hidden { get; set; }
}

The above class is part of my DbContext which is used by DataService - so a basic implementation.

Is there any way of preventing customer_hidden from being returned to client using some DataAnnotation perhaps?

Foi útil?

Solução

I would recommend that you don't use the same objects in the data layer and the service layer, since it creates a tight coupling between the server and the client.

This is demonstraded in your question, I suppose: You want a flag on the server side saying that the customer is hidden, info that the client shouldn't have access to.

Instead you could use DTO's in the service layer (in the WCF service interface methods) that simply don't contain this property, e.g.

public class CustomerDto
{
  public int customer_id { get; set; }

  public string customer_name { get; set; }
}

You would need some kind of mapping between the entity objects and the DTO's, but there are nice third-party libraries that can handle that for you. I use Automapper.

The loose coupling you get through this approach gives you a range of advantages. Consider for instance that you extend or change the customer object on the server side and add address data, telephone numbers etc. Or rename customer_id to CustomerId. All of these updates can be hidden from the client through this approach, you just keep the mapping (in case of added fields) or change the mapping slightly (in case of renamed fields).

Then, when the client also has been updated to support the new functionality, you extend the service layer to include the new properties.

If you want to take this approach the whole way, you should also consider mapping the DTO's back to client (GUI) entities that are specialized for use client-side. Recently I needed to have a flag on a client object that indicated if the object had been printed or not. This kind of flag has no place in the service layer or on the server, but since I had created client objects it was no problem.

A disadvantage of this approach may be properties that you forget to add in the service layer comes out null on the client side, but in my experience these kind of bugs are rather easy to track down.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top