Search code examples
c#wcf

Returning List<T> with WCF service


I got an Employee class and each employee has a list of applied leaves. Is it possible to have the list AppliedLeave as a [DataMember] in WCF?

[DataContract]
public class Employee
{
    [DataMember]
    public string UserID { get; set; }

    [DataMember]
    public int EmployeeNumber { get; set; }

    [ForeignKey("EmployeeUserID")]
    [DataMember]
    public List<Leave> AppliedLeave
    {
        get { return _appliedLeaves; }
        set { _appliedLeaves = value; }
    }

    private List<Leave> _appliedLeaves = new List<Leave>();
    ...
 }

Is there any other way to do this?

thank you for your consideration of this matter

I extend my Question

This is my Leave Class:

[DataContract]
public class Leave
{

    [Key()]
    [DataMember]
    public Guid LeaveId { get; set; }

    [DataMember]
    public string LeaveType { get; set; }

    [DataMember]
    public DateTime StartDate { get; set; }

    [DataMember]
    public string EmployeeUserID { get; set; }

}

this shows ServiceContract ---->

[ServiceContract]
public interface IEmployeeService
{
    [OperationContract]
    Employee GetEmployeeByUserId(string userId);

    [OperationContract]
    void AssignSupervisor(string userId, string supervisorUserId);

    [OperationContract]
    void DeleteEmployeeByUserId(string userId);

....
}

In Client application,

EmployeeServiceClient employeeService = new EmployeeServiceClient();

Employee employee = employeeService.GetEmployeeByUserId(id);

But when Employee gathered from the service its shows Null for leaves,

enter image description here

Can somebody help me? what have I done wrong here?


Solution

  • Yes, it is possible to return generics from WCF service operations.

    But by default they are casted to Array on client side. This can be customized while proxy generation.

    WCF: Serialization and Generics

    Also you have to decorate the service with all the types to which generics can be resolved, using KnownTypeAttribute.

    Known Types and the Generic Resolver