[Tips] Entity Framework and JSON

[Tips] Entity Framework and JSON

需求

提供JSON的格式資料,但是不要將所有的entity欄位都輸出.

 

方式

 

輸出所有欄位

   1: using (MyStockEntities entities = new MyStockEntities())
   2: {
   3:     JavaScriptSerializer js = new JavaScriptSerializer();
   4:     return js.Serialize(entities.CodeStocks);
   5: }

 

輸出需要的欄位

   1: using (MyStockEntities entities = new MyStockEntities())
   2: {
   3:     JavaScriptSerializer js = new 
   4:     JavaScriptSerializer();
   5:     var results = from cols in entities.CodeStocks
   6:         select new
   7:         {
   8:             StockId = cols.StockId,
   9:             StockName = cols.StockName,
  10:             StockType = cols.StockType
  11:         };
  12:     return js.Serialize(results);
  13: }