简体   繁体   中英

WCF Create generic property List<T> in DataMember class

I'm creating WCF service which have two OperationContract returning list of records in JSON format

Sample code:

 List<Response> GetCollegeList()
 List<Response> GetStudentList(int CollegeId)
public class Colleges
{
    public int CollegeId { get; set; }
    public string CollegeName { get; set; }        
}
public class Students
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }

}
public class Response
{
    public string status_code { get; set; }
    public string responsemessage { get; set; }
    public List<College> data { get; set; }
}

I want to create generic List for Student and College

public List<College> data { get; set; }

How to use generic List for service Response data

public List<Response> GetCollegeList()
{
        List<Colleges> collegelist = new List<Colleges>();
        List<Response> response = new List<Response>();      
        dt =obj.GetCollegeList();

        if (dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                collegelist.Add(
                   new Colleges
                   {
                       CollegeId = Convert.ToInt32(row["CollegeId"].ToString()),
                       CollegeName = row["CollegeName"].ToString() 
                   }
                 );
            }
        }

        response.Add(new Response { status_code = "success", responsemessage = "College List", data = collegelist });


    return response;
}

You should make Response to generic:

public class Response<T>
{
    public string status_code { get; set; }
    public string responsemessage { get; set; }
    public T data { get; set; }
}

Then return Response<List<Colleges>> from GetCollegeList() as following:

public Response<List<Colleges>> GetCollegeList()
{
    List<Colleges> collegelist = new List<Colleges>();

    dt =obj.GetCollegeList();

    if (dt.Rows.Count > 0)
    {
        foreach (DataRow row in dt.Rows)
        {
            collegelist.Add(
               new Colleges
               {
                   CollegeId = Convert.ToInt32(row["CollegeId"].ToString()),
                   CollegeName = row["CollegeName"].ToString() 
               }
             );
        }
    }
    Response<List<Colleges>> response = Response<List<Colleges>>()
    {
        status_code = "success", 
        responsemessage = "College List", 
        data = collegelist 
    };


    return response;
}

You can use this approach for Students as Response<List<Students>> as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM