2017-02-12 85 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; 
    }