Avoid serializing certain properties in REST services

I have a .Net application separated on the client and server side, and the server provides REST services (using WCF). I have service definitions like these:

[WebGet(UriTemplate = "/Customers/{id}")]
Customer GetCustomerById(string id);

[WebGet(UriTemplate = "/Customers")]
List<Customer> GetAllCustomers();

The Customer class and its friends map to a database using Fluent NHibernate with Lazy Loading. If I return from a service outside the scope of the session, the service call will fail because it cannot serialize the link lazy loaded property Orders (see def class at the end). The problem is that I need it to be lazily loaded, since I do not want my GetAllCustomersservice to receive all the specified Orders. Therefore, I want to somehow notify the serializer so that it does not try to serialize GetAll Orders. But keep in mind that the same property must be serialized to GetCustomerById - so I have to specify this in the service. It can be done?!

Classes:

public class Customer
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Order> Orders { get; set; }
}

public class Order
{
    public virtual int Id { get; set; }
    // ++ 
}
+3
4

WCF - , , , , , . [DataMember], , , :

[DataContract]
public class Customer
{
    [DataMember]
    public virtual int Id { get; set; }

    [DataMember]
    public virtual string Name { get; set; }

    // not decorate 
    public virtual IList<Order> Orders { get; set; }
} 

UPDATE , . , CustomerBase ( ), ( ) CustomerWithOrders ( ). .

, , DataContractSerializerOperationBehavior IDataContractSurrogate :

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.idatacontractsurrogate.aspx

http://msdn.microsoft.com/en-us/library/system.servicemodel.description.datacontractserializeroperationbehavior_members.aspx

+3

DTO , Automapper nhib DTO. , sprcialised , , , , .

+2

GetAllCustomers. .

[DataContract]
public class CustomerSummary
{
   // Have properties that represent the summary of the customer
}

WebGet(UriTemplate = "/Customers/{id}")]    
Customer GetCustomerById(string id);    

[WebGet(UriTemplate = "/Customers")]    
List<CustomerSummary> GetAllCustomers();

EmitDefaultValue DataMember Orders:

[DataContract]       
public class Customer       
{       
   [DataMember]       
   public virtual int Id { get; set; }       

   [DataMember]
   public virtual string Name { get; set; }       

   [DataMember(IsRequired = false, EmitDefaultValue = false)]
   public virtual IList<Order> Orders { get; set; }       
}

Orders null, GetAllCustomers .

+1

Lazy loading only works as part of a sleep mode session. Do not do this by wire. You need to eagerly get a collection or use OOP inheritance and return from your web method a class that does not have this collection at all, especially if consumers do not need it.

0
source

Source: https://habr.com/ru/post/1766160/


All Articles