2017-02-12 81 views
1

我想轉換下面的代碼來返回數組結果。但我無法讓它工作。我對Linq框架相當陌生。從Linq查詢返回數組

這裏是我的代碼:

// GETAll api/category 
public IEnumerable<Category> GetAll() 
{ 
    nopMass db = new nopMass(); 

    var model = db.Categories.Where(x => x.ParentCategoryId == 0); 

    return model.ToArray(); 
} 

這是我想它返回

// GETAll api/category 
public IEnumerable<Category> GetAll() 
{ 
    return new Category[] 
    { 
     new Category 
     { 
      ParentCategoryId = 1, 
      Name = "New Vehicles" 
     }, 
     new Category 
     { 
      ParentCategoryId = 2, 
      Name = "Used Vehicles" 
     } 
    }; 
} 

當我在HTML訪問第一個代碼,我沒有得到顯示的結果是什麼。第二個代碼給出了一個輸出。

這裏是Html和jQuery代碼

<ul id="products" /> 

<script> 
    var uri = 'api/category'; 

    $(document).ready(function() { 
     // Send an AJAX request 
     try 
     { 
      $.getJSON(uri) 
       .done(function (data) { 
        // On success, 'data' contains a list of products. 
        $.each(data, function (key, item) { 
         // Add a list item for the product. 
         $('<li>', { text: formatItem(item) }).appendTo($('#products')); 
        }); 
       }); 
     } 
     catch (e) { 
      alert(e.message); 
     } 
}); 

function formatItem(item) { 
    return item.Name; 
} 

</script> 
+0

請求的結果只是一個例子。當我調試該行時,我確實看到了值被返回,但它不顯示在前端:( – Orion

+2

如果mopMass是一個DBContext,您應該在處理完它後真正處理它。 –

+0

看起來像.done在JQuery中沒有執行 – Orion

回答

2

這裏是你的答案重構LINQ

// GETAll api/category 
public IEnumerable<Category> GetAll() { 
    using(var db = new nopMass()) { 

     var cats = db.Categories 
        .Where(x => x.ParentCategoryId == 0) 
        .AsEnumerable() 
        .Select(cat => new Category { 
         ParentCategoryId = cat.ParentCategoryId, 
         Name = cat.Name 
        }) 
        .ToArray(); 

     return cats; 
    } 
} 

而且,正如評論中提到的那樣,確保db上下文在使用後正確處置。

+0

我得到以下錯誤,「實體或複雜類型'WebAPI.Models.Category'不能在LINQ to Entities查詢中構建。」我想我需要創建一個單獨的Category對象,它是不是DBContext對象的一部分,這將涉及更多的編碼,而不是我下面的答案? – Orion

+0

@Orion您可以添加'AsEnumerable','ToList'或其他表達式,在執行「選擇」之前枚舉集合 – Nkosi

+1

@Orion檢查更新的答案。 – Nkosi

1

一個花了一些時間,但我終於得到它的工作:)

// GETAll api/category 
    public IEnumerable<Category> GetAll() 
    { 
     nopMass db = new nopMass(); 

     var model = db.Categories.Where(x => x.ParentCategoryId == 0); 

     Category[] cats = new Category[model.Count()]; 

     int index = 0; 
     foreach (var cat in model) 
     { 
      cats[index] = new Category { ParentCategoryId = cat.ParentCategoryId, Name = cat.Name }; 
      index++; 
     } 

     return cats; 
    }