简体   繁体   English

C#Web API oData筛选器失败

[英]C# Web API oData Filter fail

When I define my end point API as below returning all columns, oData $filter, $Skip, $filter work fine. 当我如下定义端点API时,返回所有列,oData $ filter,$ Skip,$ filter工作正常。

 [EnableQuery]
        public IQueryable<MyList> GetMyLists()
        {
            return db.MyLists;//directly from entity table
        }

but when I select only certain columns like shown below, oData $filter, $Skip, $filter fail. 但是当我仅选择某些列,如下所示时,oData $ filter,$ Skip,$ filter失败。 Any ideas? 有任何想法吗?

public IQueryable<MyResult> GetMyLists()
        {
            return db.MyLists.Select(x => new MyResult
            {
                Trade_Name = x.Trade_Name,
                price = x.price,
                remarks = x.remarks,
                Comment = x.Comment,
                GenericGroupNumber = x.GenericGroupNumber
            }); 
        }

I defined MyResult Class as: 我将MyResult类定义为:

public class MyResult
    {
        public string Trade_Name;
        public decimal? price;
        public string remarks;
        public string Comment;
        public string GenericGroupNumber;

    }

Any guidance is greatly appreciated. 任何指导,不胜感激。

The class MyResult has no [key] column and don't map to a table in the EDMX model. MyResult类没有[key]列,并且不映射到EDMX模型中的表。 It is considered as a complex entity (like stored procedure). 它被视为复杂的实体(如存储过程)。 so you can't apply $filter, $skip. 因此您无法应用$ filter,$ skip。

oData is designed to work with the entities described in the EDMX model in the WebApiConfig.cs file, any entity outside of that will not allow you to apply $filter, $skip, etc. oData旨在与WebApiConfig.cs文件中EDMX模型中描述的实体一起使用,超出该实体的任何实体将不允许您应用$ filter,$ skip等。

You will need to define that entity in your EDMX model and place it in a controller of it's own named based on the entity name for it to work. 您将需要在EDMX模型中定义该实体,并将其放置在根据实体名称自己命名的控制器中,该实体才能起作用。

class MyResultsController : ApiController {
    public IQueryable<MyResult> GetMyResults()
    {
        return db.MyLists.Select(x => new MyResult
        {
            Trade_Name = x.Trade_Name,
            price = x.price,
            remarks = x.remarks,
            Comment = x.Comment,
            GenericGroupNumber = x.GenericGroupNumber
        }); 
    }
}

Then make sure you map MyResult correctly in the WebApiConfig . 然后确保您在WebApiConfig正确映射了MyResult

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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