Using IQueryable select to filter columns

asp.net-mvc asp.net-web-api c# entity-framework iqueryable

Question

I've been exploring WEB API based on the guide at www.asp.net, and I've run into a problem when trying to filter columns from a table.

My code is simply this:

    // GET api/Admin
    public IEnumerable<Product> GetProducts(testvar = "")
    {
        IQueryable<Product> productString = db.Products;

        if (testvar != "")
        {
            productString = productString.ToList().Select(i => new Product
            {
                Name = i.Name
            }).AsQueryable();
        }
        return productString;
    }

All I want to do is retrieve the Name column from the Product table for my JSON. However, instead of getting something like:

[{"Name":"Hammer"}] or [{"$id":"1","Name":"Hammer"}]

I'm getting:

[{"$id":"1","Id":0,"Name":"Hammer","Price":0.0,"ActualCost":0.0}]

The Price and ActualCost values are normally 16.99 and 20.00, but instead of removing them, they are just returned as 0. Same for Id.

Is there an easy way to stop it returning the Id, Price and ActualCost? Perhaps I'm missing something really simple, but the below two links are the closest I've come to finding something that might work.

IQueryable C# Select

The entity cannot be constructed in a LINQ to Entities query

As per the guide I've been using ( http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/using-web-api-with-entity-framework,-part-1 ) I'm working in an MVC 4 project with the Orders, Projects and OrderDetails tables.

Thanks

1
1
5/23/2017 11:50:44 AM

Accepted Answer

I figured it out. I just assigned the Product to a new variable and made the select call on that, and it worked perfectly.

So now instead of:

productString = productString.ToList().Select(i => new Product
        {
            Name = i.Name
        }).AsQueryable();

I have

var productInfos =
                    from i in productString
                    select new { i.Name };
                    newVariable.Add(productInfos);

I then return the newVariable, which is a list of objects instead of an IEnumerable of Products.

0
4/28/2013 5:44:38 PM

Popular Answer

You are still returning the full Product entity type, so even though you are projecting to a collection of new Product, the uninitialized properties will still have their default values (0 for int).

You should create a new type which just contains the properties (e.g. ProductInfo) you wish to expose and return a collection of this type.

Alternatively, if your service supported the $select query option, the client could perform projections.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow