Asp.net 5 WebApi 2.0部分响应

时间:2015-09-09 08:41:58

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

我正在使用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*/})
}

但我不知道该怎么做。任何熟悉此事的人都请帮忙。

1 个答案:

答案 0 :(得分:0)

我不太清楚你是否需要协助实际将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);
    }
}