简体   繁体   中英

Using IQueryable select to filter columns

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

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 (eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM