Orion
Orion

Reputation: 452

Return Array from Linq Query

I'm trying to convert the following code to return an array result. But am unable to get it to work. I'm fairly new to the Linq framework.

Here is the Code I have:

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

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

    return model.ToArray();
}

This is what I want it to return

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

When I access the first code in HTML I don't get a result displaying. The second code gives an output.

Here is Html and Jquery Code

<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>

Upvotes: 1

Views: 2320

Answers (2)

Nkosi
Nkosi

Reputation: 247018

Here is Your answer refactored 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;
    }
}

And also, as mentioned in the comments, making sure the the db context is disposed of properly after use.

Upvotes: 2

Orion
Orion

Reputation: 452

A took some time, but I finally got it to work :)

    // 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;
    }

Upvotes: 1

Related Questions