【问题标题】:Asp.net 5 WebApi 2.0 partial responseAsp.net 5 WebApi 2.0 部分响应
【发布时间】:2015-09-09 08:41:57
【问题描述】:

我正在研究 LinQ to Entity, 这是我的工作代码:

        var products = from p in AppContext.Products
                       join ... //joins tables
                       where ... //conditions
                       select p;

        var result = products.OrderBy(p => p.Name);

        //Move it to custom format.
        return result.Select(p => new
            {
                p.Id,
                p.Name,
                p.Description,
                ...
                /*This looks ugly and need to be moved out to somewhere else*/
                Categories = FindCategories(p.Id, true),
                MetaData = AppContext.ProductMetas.Where(pm => pm.ProductId == p.Id),
                Photos = AppContext.ProductPhotos.Where(pp => pp.ProductId == p.Id)
            }).Skip(skip).Take(take);

但是,我想将“返回新...”部分移到其他地方(在将对象转换为 json 时最好注入 asp.net api 处理程序)。例如:

//GetAll()
...
var products = from ... in ... select p;
return products;

//How to register some handler 
var results = new List<object>();
foreach (var product in resultSet) {
    //merge objects into result set
    results.Add(new {/*Merge properties together*/})
}

但我不知道该怎么做。有熟悉这个的,请帮忙。

【问题讨论】:

    标签: c# asp.net-web-api linq-to-sql httphandler


    【解决方案1】:

    我不太清楚您是否需要将 Linq 中的对象实际映射到实体或如何将此逻辑添加到 ASP.NET 5 路由的帮助,我假设是后者。 一种方法是创建一个 DTO,其中包含您需要的实体和关系数据,如下所示:

    public class ProductDTO
    {
        public int Id {get;set;}
        public string Name {get;set;}
        public List<Category> Categories {get;set;}
        ...
    }
    

    然后您需要创建一个控制器来处理请求:

    [Route("api/[controller]")]
    public class ProductController : Controller
    {
        [HttpGet]
        public IActionResult GetAll()
        {
            var products = //..make call to service or query to get products..
    
            var results = new List<ProductDTO>();
            foreach (var product in products) 
            {
                // merge objects into new ProductDTO collection
                results.Add(a=> new ProductDTO() {Id = a.Id, Name = a.Name ...});
            }
            return new JsonResult(values);
        }
    }
    

    【讨论】:

    • 谢谢@corkington,实际上我就是这样做的。但是,我这里需要的是:` //这应该是动态字段。如果客户现在只需要一个“名称”,然后它调用另一个请求并需要“代码、价格、数量”怎么办? results.Add(a=> new ProductDTO() {Id = a.Id, Name = a.Name ...}); `
    猜你喜欢
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多