2013-12-17 2 views
2

WCF의 편안한 서비스를 개발하여 json 형식으로 데이터를 노출합니다. 현재 데이터를 데이터베이스로 가져온 다음 각 행을 반복하여 목록에 넣은 다음 반환합니다. 그러나이 반복을 건너 뛰고 데이터 테이블을 목록으로 직접 캐스팅하려고합니다.데이터 테이블을 WCF의 List로 변환

나는 더 이상 내 서비스에 모든 열 매핑을 작성해야합니다 이런 식으로 ...

현재 코드 :

[OperationContract] 
[WebInvoke 
(
    Method = "GET", 
    BodyStyle = WebMessageBodyStyle.Bare, 
    ResponseFormat = WebMessageFormat.Json, 
    UriTemplate = "Id/All" 
) 
] 

DataTable dt = new DataTable(); 

dt = myData; 

List<myCls> lstAllmyCls = new List<myCls>(); 

foreach (DataRow dr in dt.Rows) 
{ 
    DataContactClass DataContactCls= new DataContactClass(); 
    DataContactCls.Id = Convert.ToInt32(dr["Id"]); 
    DataContactCls.Name = dr["Name"].ToString(); 
    myCls.Add(DataContactCls); 
} 

return myCls.ToArray(); 

변경된 코드 : 여기

var convertlist = (from dr in dt.AsEnumerable() 
        select new DataContactCls() 
        { 
         Id = Convert.ToInt32(dr["Id"]), 
         Name = dr["Name"].ToString() 
        }).ToList(); 

하지만 json으로 목록 데이터를 다시 작성하는 동안 피하고 싶은 열 이름을 제공하고 있습니다.

누구든지 더 유용한 것을 제안 할 수 있습니까?

답변

1

당신은 아래의 코드를

private List<T> ConvertToList<T>(DataTable dt) 
    { 
     var columnNames = dt.Columns.Cast<DataColumn>() 
      .Select(c => c.ColumnName) 
      .ToList(); 

     var properties = typeof(T).GetProperties(); 

     return dt.AsEnumerable().Select(row => 
      { 
       var objT = Activator.CreateInstance<T>(); 

       foreach (var pro in properties) 
       { 
        if (columnNames.Contains(pro.Name)) 
         pro.SetValue(objT, row[pro.Name]); 
       } 

       return objT; 
      }).ToList(); 

    } 

주를 시도 할 수 그때 내가 이런 식으로했고, 그것을 JSON 데이터 벌금을 생성 반사를 여전히 답을 찾고

+0

방법 : 오류 방법에 대한 과부하는 'SetValue는'2 인자 소요됩니다. 나는 현재의 코드가 더 실현 가능할 것이라고 생각하지만, 어떤 방법으로도 두 가지를 모두 체크 아웃 할 것이다. – user2519971

0

사람을 사용하면 성능에 영향이 항상있다.

IService.cs 코드 :

[OperationContract] 
     [WebInvoke(Method = "GET", UriTemplate = "/GetProducts/", 
      BodyStyle = WebMessageBodyStyle.WrappedRequest, 
      RequestFormat = WebMessageFormat.Json, 
      ResponseFormat = WebMessageFormat.Json)] 
     List<Dictionary<string, string>> GetProducts(); 

Service.cs 코드 :

public List<Dictionary<string, string>> GetProducts() 
{ 
    DataTable dtTable = loadProduct(); 
    Dictionary<string, string> dic = new Dictionary<string, string>(); 
    List<Dictionary<string, string>> plist = new List<Dictionary<string, string>>(); 
       foreach (DataRow dr in dtTable.Rows) 
       { 

        dic.Add(dr[0].ToString(), dr[1].ToString()); 

       } 
       plist.Add(dic); 
       return plist; 
} 
관련 문제